package cn.rkylin.oms.order.service;

import java.math.BigDecimal;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

//import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.github.pagehelper.PageInfo;

import cn.rkylin.apollo.common.util.HttpUtils;
import cn.rkylin.apollo.common.util.SnoGerUtil;
import cn.rkylin.core.service.ApolloService;
import cn.rkylin.oms.aftersale.event.service.IAfterSaleEventService;
import cn.rkylin.oms.aftersale.resend.dao.IAfterSaleResendDAO;
import cn.rkylin.oms.aftersale.sysrefund.domain.SysRefund;
import cn.rkylin.oms.aftersale.sysrefund.servcie.ISysRefundService;
import cn.rkylin.oms.aftersale.sysrefund.vo.SysRefundVO;
import cn.rkylin.oms.aftersale.sysreturn.service.ISysReturnService;
import cn.rkylin.oms.aftersale.sysreturn.vo.SysReturnVO;
import cn.rkylin.oms.area.dao.ITopAreaDAO;
import cn.rkylin.oms.area.domain.TopArea;
import cn.rkylin.oms.area.service.ITopAreaService;
import cn.rkylin.oms.common.base.AbstractAdapterFactory;
import cn.rkylin.oms.common.consts.OrderOperStatusConsts;
import cn.rkylin.oms.common.consts.YesNoConst;
import cn.rkylin.oms.common.context.CurrentUser;
import cn.rkylin.oms.common.context.WebContextFactory;
import cn.rkylin.oms.common.dto.DBLog;
import cn.rkylin.oms.common.utils.CodeUtil;
import cn.rkylin.oms.common.utils.LogUtil;
import cn.rkylin.oms.goods.domain.GoodsSku;
import cn.rkylin.oms.goods.service.IGoodsService;
import cn.rkylin.oms.goods.vo.GoodsSkuVO;
import cn.rkylin.oms.item.dao.ItemDAOImpl;
import cn.rkylin.oms.item.service.IItemService;
import cn.rkylin.oms.item.vo.ItemVO;
import cn.rkylin.oms.item.vo.SkuVO;
import cn.rkylin.oms.order.dao.IOrderDAO;
import cn.rkylin.oms.order.dao.IOrderSkuDAO;
import cn.rkylin.oms.order.domain.Order;
import cn.rkylin.oms.order.domain.OrderSku;
import cn.rkylin.oms.order.vo.AssignVO;
import cn.rkylin.oms.order.vo.DownLoadVO;
import cn.rkylin.oms.order.vo.OrderExportVO;
import cn.rkylin.oms.order.vo.OrderInfoList;
import cn.rkylin.oms.order.vo.OrderInfoVO;
import cn.rkylin.oms.order.vo.OrderSkuVO;
import cn.rkylin.oms.order.vo.OrderVO;
import cn.rkylin.oms.order.vo.OrderVOForEvent;
import cn.rkylin.oms.push.request.PushTradeMemo;
import cn.rkylin.oms.system.logistics.dao.ILogisticsDAO;
import cn.rkylin.oms.system.logistics.vo.LogisticsVO;
import cn.rkylin.oms.system.shop.dao.IShopDAO;
import cn.rkylin.oms.system.shop.dao.IShopStorDAO;
import cn.rkylin.oms.system.shop.domain.ShopStor;
import cn.rkylin.oms.system.shop.service.IShopService;
import cn.rkylin.oms.system.shop.service.IShopStorService;
import cn.rkylin.oms.system.shop.vo.ShopStorVO;
import cn.rkylin.oms.system.shop.vo.ShopVO;
import cn.rkylin.oms.system.storage.dao.IStorDAO;
import cn.rkylin.oms.system.storage.domain.Stor;
import cn.rkylin.oms.system.storage.service.IStorService;
import cn.rkylin.oms.warehouse.shiporder.domain.Shiporder;
import cn.rkylin.oms.warehouse.shiporder.service.IShiporderService;
import cn.rkylin.oms.warehouse.shiporder.util.SnCodeExtractor;
import cn.rkylin.oms.warehouse.shiporder.vo.ShiporderSkuVO;
import cn.rkylin.oms.warehouse.shiporder.vo.ShiporderVO;
import cn.rkylin.oms.warehouse.stock.service.IStockService;
import cn.rkylin.oms.warehouse.stock.vo.StockVO;

@Service("orderService")
public class OrderServiceImpl extends ApolloService implements IOrderService {
    private static final Log logger = LogFactory.getLog(OrderServiceImpl.class);

    @Autowired
    private SnCodeExtractor snCodeExtractor;

    /**
     * 日志类
     */
    @Autowired
    private LogUtil logUtil;

    @Autowired
    private IStorDAO stroDAO;

    @Autowired
    private IOrderDAO orderDAO;

    @Autowired
    private IOrderSkuDAO orderSkuDAO;

    @Autowired
    private IShopDAO shopDAO;
    
    @Autowired
    private IShopStorDAO shopStorDAO;

    @Autowired
    private IAfterSaleEventService afterSaleEventService;

    @Autowired
    private ISysRefundService sysRefundService;

    @Autowired
    private ISysReturnService sysReturnService;

    @Autowired
    private IShiporderService shiporderService;

    @Autowired
    private IStorService storService;

    @Autowired
    public IStockService stockService;

    @Autowired
    public IShopService shopService;

    @Autowired
    public IAfterSaleResendDAO resendDAO;

    @Autowired
    private IGoodsService goodsService;

    @Autowired
    private IShopStorService shopStorService;
    
    @Autowired
    public ITopAreaService topAreaService;

    @Autowired
    private ILogisticsDAO lgstDAO;

    @Autowired
    private ITopAreaDAO topAreaDAO;

    @Value("${executor.return.downLoad.ectrade.url}")
    private String ectradeUrl;

    @Value("${executor.return.downLoad.sysOrder.url}")
    private String sysOrderUrl;

    @Value("${gateway}")
    private String gateway;

    @Value("${oms.address}")
    private String omsAddres;
    
    @Autowired
    private IItemService itemService;

    private static final String AFTERSALE_FLAG = "<span class='badge badge-orange'> </span>";
    private static final String COMBIN_FLAG = "<span class='badge badge-blue'> </span>";

    public PageInfo<OrderVO> findByWhere(int page, int rows, OrderVO orderVO) throws Exception {
        logger.error("【订单查询条件.prjId】-->" + orderVO.getPrjId());
        logger.error("【订单查询条件.shopId】-->" + orderVO.getShopId());
        PageInfo<OrderVO> orderVOList = findPage(page, rows, "pageSelectOrder", orderVO);
        // if (orderVOList.getList() != null && orderVOList.getList().size() >
        // 0) {
        // for (int i = 0; i < orderVOList.getList().size(); i++) {
        // // 退款的场合
        // Map<String, String> mapRefund = new HashMap<String, String>();
        // mapRefund.put("orderId", orderVOList.getList().get(i).getOrderId());
        // mapRefund.put("isCancel", "n");
        // mapRefund.put("deleted", "n");
        // List<SysRefund> listSysRefund =
        // sysRefundService.findSysRefundList(mapRefund);
        // if (listSysRefund != null && listSysRefund.size() > 0) {
        // orderVOList.getList().get(i).setCustomerService(AFTERSALE_FLAG);
        // } else {
        // // 退货的场合
        // SysReturnVO sysReturn = new SysReturnVO();
        // sysReturn.setSourceId(orderVOList.getList().get(i).getOrderId());
        // sysReturn.setDeleted("n");
        // sysReturn.setIsCancel("n");
        // List<SysReturnVO> listReturn =
        // sysReturnService.querySysReturnVOList(sysReturn);
        // if (listReturn != null && listReturn.size() > 0) {
        // orderVOList.getList().get(i).setCustomerService(AFTERSALE_FLAG);
        // } else {
        // // 补发的场合
        // ResendVO resend = new ResendVO();
        // resend.setSourceId(orderVOList.getList().get(i).getOrderId());
        // resend.setDeleted(YesNoConst.NO);
        // resend.setCancelStatus(YesNoConst.NO);
        // List<ResendVO> resendList = resendDAO.seleteByCondition(resend);
        // if (resendList != null && resendList.size() > 0) {
        // orderVOList.getList().get(i).setCustomerService(AFTERSALE_FLAG);
        // } else {
        // orderVOList.getList().get(i).setCustomerService("");
        // }
        // }
        // }
        // }
        // }
        return orderVOList;
    }

    /**
     * 要分派的数据进行check
     *
     * @return
     */
    private Map<String, Object> checkOrderSkuList(AssignVO assigObject) throws Exception {
        Map<String, Object> returnMap = new HashMap<String, Object>();
        if (assigObject == null) {
            returnMap.put("success", "n");
            returnMap.put("errormessage", "没有可分派的数据");
            return returnMap;
        }

        if (assigObject.getArrSku() == null || assigObject.getArrSku().size() <= 0) {
            returnMap.put("success", "n");
            returnMap.put("errormessage", "没有可分派的数据");
            return returnMap;
        }

        if (assigObject.getShiporder() == null) {
            returnMap.put("success", "n");
            returnMap.put("errormessage", "缺少出库单信息");
            return returnMap;
        }

        Shiporder shiporder = assigObject.getShiporder();
        // 收货人不能为空
        if (StringUtils.isBlank(shiporder.getCons())) {
            returnMap.put("success", "n");
            returnMap.put("errormessage", "收货人不能为空");
            return returnMap;
        }

        // 固定电话与手机至少要输入一个
        if (StringUtils.isBlank(shiporder.getConsTel()) && StringUtils.isBlank(shiporder.getConsMobile())) {
            returnMap.put("success", "n");
            returnMap.put("errormessage", "固定电话与手机至少要输入一个 手机");
            return returnMap;
        }

        // if (!isMobile(shiporder.getConsMobile())) {
        // returnMap.put("success", "n");
        // returnMap.put("errormessage", "手机输入不正确");
        // return returnMap;
        // }

        // if (!isFixedPhone(shiporder.getConsTel())) {
        // returnMap.put("success", "n");
        // returnMap.put("errormessage", "固定电话输入不正确");
        // return returnMap;
        // }

        // 收货人地址不能为空
        if (StringUtils.isBlank(shiporder.getConsAddr())) {
            returnMap.put("success", "n");
            returnMap.put("errormessage", "收货人地址不能为空");
            return returnMap;
        }

        // 省不能为空
        if (StringUtils.isBlank(shiporder.getProvName())) {
            returnMap.put("success", "n");
            returnMap.put("errormessage", "省不能为空");
            return returnMap;
        }

        // 市不能为空
        if (StringUtils.isBlank(shiporder.getCityName())) {
            returnMap.put("success", "n");
            returnMap.put("errormessage", "市不能为空");
            return returnMap;
        }

        // 区不能为空
//        if (StringUtils.isBlank(shiporder.getDistName())) {
//            returnMap.put("success", "n");
//            returnMap.put("errormessage", "区不能为空");
//            return returnMap;
//        }

        // 发货仓库不能为空
        if (StringUtils.isBlank(shiporder.getStorId())) {
            returnMap.put("success", "n");
            returnMap.put("errormessage", "发货仓库不能为空");
            return returnMap;
        }

        if ("y".equals(assigObject.getEmptyLgstCompany()) && StringUtils.isBlank(shiporder.getLgstId())) {
            returnMap.put("success", "n");
            returnMap.put("questionLgstId", "物流公司为空，是否确认分派？");
            return returnMap;
        }

        // 订单存在未废弃的退款单，不能取消合并
        if ("y".equals(assigObject.getHasrefund())) {
            Map<String, String> mapRefund = new HashMap<String, String>();
            mapRefund.put("orderId", assigObject.getOrderId());
            mapRefund.put("isCancel", "n");
            mapRefund.put("deleted", "n");
            List<SysRefund> listSysRefund = sysRefundService.findSysRefundList(mapRefund);
            if (listSysRefund != null && listSysRefund.size() > 0) {
                returnMap.put("success", "n");
                returnMap.put("questionhasrefund", "该订单存在未废弃的退款单,是否确认分派");
                return returnMap;
            }
        }

        List<OrderSkuVO> listOrderSku = assigObject.getArrSku();
        boolean flg = false;
        for (int i = 0; i < listOrderSku.size(); i++) {
            OrderSkuVO orderskuVO = listOrderSku.get(i);

            // 全是虚拟商品不能分派

            // 要发货数必须至少填写一个，且大于0。没有则给出提示信息：【请输入要发货数】
            if (StringUtils.isBlank(orderskuVO.getAddShippingQty())) {
                // returnMap.put("success", "n");
                // returnMap.put("errormessage", "要发货数必须至少填写一个，且大于0的数字。");
                // return returnMap;
                continue;
            }
            flg = true;
            if (!StringUtils.isNumeric(orderskuVO.getAddShippingQty())) {
                returnMap.put("success", "n");
                returnMap.put("errormessage", "要发货数必须至少填写一个，且大于0的数字。");
                return returnMap;
            }
            if (Integer.valueOf(orderskuVO.getAddShippingQty()).intValue() <= 0) {
                returnMap.put("success", "n");
                returnMap.put("errormessage", "要发货数必须至少填写一个，且大于0的数字。");
                return returnMap;
            }

            // 要发货数大于待发货数
            OrderSkuVO parm = new OrderSkuVO();
            parm.setOrderSkuId(orderskuVO.getOrderSkuId());
            parm.setOrderId(assigObject.getOrderId());
            OrderSkuVO vo = orderSkuDAO.getOrderSkuList(parm).get(0);
            int qty = vo.getQty() != null ? vo.getQty().intValue() : 0;
            int shippingQty = vo.getShippingQty() != null ? vo.getShippingQty().intValue() : 0;
            int shipedQty = vo.getShipedQty() != null ? vo.getShipedQty().intValue() : 0;
            if (qty - shippingQty - shipedQty < Integer.valueOf(orderskuVO.getAddShippingQty()).intValue()) {
                returnMap.put("success", "n");
                returnMap.put("errormessage", "要发货数大于待发货数。");
                return returnMap;
            }

            // 要发货数大于可分派数 需要校验网店开关，并且发货仓库不能为空
            OrderVO orderVO = orderDAO.findById(vo.getOrderId());
            ShopVO shopVO = shopService.getShopById(orderVO.getShopId());
            if (shopVO != null && "y".equals(shopVO.getIsCheckCanallotqty())) {
                StockVO stock = stockService.getStock(orderVO.getEntId(), orderVO.getPrjId(), vo.getSkuId(), shiporder.getStorId());
                if (stock != null && stock.getCanallotQty() != null) {
                    if (stock.getCanallotQty() < Integer.valueOf(orderskuVO.getAddShippingQty()).intValue()) {
                        returnMap.put("success", "n");
                        returnMap.put("errormessage", vo.getSkuCode() + "的可分派数不够。");
                        return returnMap;
                    }
                } else {
                    returnMap.put("success", "n");
                    returnMap.put("errormessage", vo.getSkuCode() + "的可分派数不够。");
                    return returnMap;
                }
            }

        }
        if (!flg) {
            returnMap.put("success", "n");
            returnMap.put("errormessage", "要发货数必须至少填写一个，且大于0的数字。");
            return returnMap;
        }
        returnMap.put("success", "y");
        return returnMap;
    }

    /**
     * 分派订单
     *
     */
    public Map<String, Object> assignOrder(AssignVO assigObject, String strPrjShortName) throws Exception {
        Map<String, Object> returnMap = new HashMap<String, Object>();
        returnMap = checkOrderSkuList(assigObject);
        if ("n".equals(returnMap.get("success"))) {
            return returnMap;
        }
        OrderVO orderVO = orderDAO.findById(assigObject.getOrderId());
        ShiporderVO vo = setShiporderInfo(orderVO, strPrjShortName, assigObject.getShiporder(), assigObject.getArrSku());
        return insertShiporderInfo(vo, assigObject.getOrderId());
    }

    /**
     * 给发货单实体赋值
     *
     * @param sysOrderVO      系统订单实体
     * @param strPrjShortName 项目简称，用于生成发货单号
     * @return
     * @throws Exception
     */
    private ShiporderVO setShiporderInfo(OrderVO sysOrderVO, String strPrjShortName, Shiporder shiporder, List<OrderSkuVO> list)
            throws Exception {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        // 发货单实体
        ShiporderVO shiporderVO = new ShiporderVO();

        // 店铺昵称
        String strShopAccount = "";
        ShopVO shopVO = AbstractAdapterFactory.getShop(sysOrderVO.getShopId());
        if (shopVO != null && StringUtils.isNotBlank(shopVO.getShopAccount())) {
            strShopAccount = shopVO.getShopAccount();
        }

        Stor stor = stroDAO.findByid(shiporder.getStorId());

        // 发货单Id
        String strShiporderId = java.util.UUID.randomUUID().toString().replaceAll("-", "");
        shiporderVO.setShiporderId(strShiporderId);
        shiporderVO.setShiporderCode("SO" + strPrjShortName + CodeUtil.getCode());
        shiporderVO.setTradeCode(sysOrderVO.getTradeCode());
        shiporderVO.setSourceId(sysOrderVO.getOrderId());
        shiporderVO.setSourceCode(sysOrderVO.getOrderCode());
        shiporderVO.setSourceType("or");
        shiporderVO.setEntId(sysOrderVO.getEntId());
        shiporderVO.setPrjId(sysOrderVO.getPrjId());
        shiporderVO.setShopId(sysOrderVO.getShopId());
        shiporderVO.setShopName(sysOrderVO.getShopName());
        shiporderVO.setShopAccount(strShopAccount);
        shiporderVO.setStorId(shiporder.getStorId());
//        shiporderVO.setStorCode(shiporder.getStorCode()); 为了安全不从画面取得，从数据库取得
//        shiporderVO.setStorName(shiporder.getStorName());
        shiporderVO.setStorName(stor.getStorName());
        shiporderVO.setStorCode(stor.getStorCode());
        shiporderVO.setLgstId(shiporder.getLgstId());
        shiporderVO.setLgstCode(shiporder.getLgstCode());
        shiporderVO.setLgstName(shiporder.getLgstName());
        shiporderVO.setLgstNo(sysOrderVO.getLgstNo());
        shiporderVO.setSourcePlatformCode(sysOrderVO.getShopType());
        shiporderVO.setOrderTime(formatter.format(sysOrderVO.getOrderTime()));
        shiporderVO.setProvName(shiporder.getProvName());
        shiporderVO.setCityName(shiporder.getCityName());
        shiporderVO.setDistName(shiporder.getDistName());
        shiporderVO.setAreaCoding(shiporder.getAreaCoding());
        shiporderVO.setCustRemark(sysOrderVO.getCustRemark());
        shiporderVO.setSalesRemark(sysOrderVO.getSalesRemark());
        shiporderVO.setRemark(sysOrderVO.getRemark());
        shiporderVO.setCons(shiporder.getCons());
        shiporderVO.setConsTel(shiporder.getConsTel());
        shiporderVO.setConsMobile(shiporder.getConsMobile());
        shiporderVO.setConsAddr(shiporder.getConsAddr());
        shiporderVO.setBuyerNick(sysOrderVO.getBuyerNick());
        shiporderVO.setPaidDate(sysOrderVO.getPaidDate());
        shiporderVO.setOrderType(sysOrderVO.getOrderType());
        shiporderVO.setPaidFee(sysOrderVO.getPaidFee());
        // 获取对应系统订单商品信息列表
        // OrderSkuVO orderSkuParm = new OrderSkuVO();
        // orderSkuParm.setOrderId(sysOrderVO.getOrderId());
        // List<OrderSkuVO> sysOrderGoodsList =
        // orderSkuDAO.getOrderSkuList(orderSkuParm);
        List<ShiporderSkuVO> shiporderSkuList = new ArrayList<ShiporderSkuVO>();
        int num = 0;
        for (int orderSkuIndex = 0; orderSkuIndex < list.size(); orderSkuIndex++) {
            ShiporderSkuVO shiporderSku = new ShiporderSkuVO();
            OrderSkuVO orderSkuParm = new OrderSkuVO();
            orderSkuParm.setOrderSkuId(list.get(orderSkuIndex).getOrderSkuId());
            OrderSkuVO sysOrderGoods = orderSkuDAO.getOrderSkuList(orderSkuParm).get(0);
            // 只有非虚拟商品才能生成发货单明细
            if ("n".equals(sysOrderGoods.getIsVirt())) {
                num++;
                if (StringUtils.isNotBlank(list.get(orderSkuIndex).getAddShippingQty())) {
                    shiporderSku.setShiporderSkuId(SnoGerUtil.getUUID());
                    shiporderSku.setShiporderId(strShiporderId);
                    shiporderSku.setOrderSkuId(sysOrderGoods.getOrderSkuId());
                    shiporderSku.setOid(sysOrderGoods.getOid());
                    shiporderSku.setSkuId(sysOrderGoods.getSkuId());
                    shiporderSku.setSkuCode(sysOrderGoods.getSkuCode());
                    shiporderSku.setSkuName(sysOrderGoods.getSkuName());
                    shiporderSku.setGoodsId(sysOrderGoods.getGoodsId());
                    shiporderSku.setGoodsCode(sysOrderGoods.getGoodsCode());
                    shiporderSku.setGoodsName(sysOrderGoods.getGoodsName());
                    if (shiporderSku.getQty() != null) {
                        shiporderSku.setQty(String.valueOf(Integer.valueOf(shiporderSku.getQty()).intValue()
                                + Integer.valueOf(list.get(orderSkuIndex).getAddShippingQty()).intValue()));
                    } else {
                        shiporderSku.setQty(list.get(orderSkuIndex).getAddShippingQty());
                    }

                    if (sysOrderGoods.getDivideOrderFee() != null && shiporderSku.getQty() != null) {
                        shiporderSku.setDivideGoodsFee(
                                (sysOrderGoods.getDivideOrderFee().divide(BigDecimal.valueOf(Integer.valueOf(shiporderSku.getQty())), 2,
                                        BigDecimal.ROUND_HALF_UP)).toString());
                    }

                    shiporderSku.setTradeCode(sysOrderGoods.getTradeCode());
                    shiporderSkuList.add(shiporderSku);
                }
            }
        }
        shiporderVO.setOrderSkuNum(num);
        shiporderVO.setShiporderSkuList(shiporderSkuList);
        return shiporderVO;
    }

    /**
     * 系统发货单插入数据库
     *
     * @param shiporderVO
     * @return
     * @throws Exception
     */
    private Map<String, Object> insertShiporderInfo(ShiporderVO shiporderVO, String orderId) throws Exception {
        Map<String, Object> returnMap = new HashMap<String, Object>();
        StringBuilder strEmptyLgst = new StringBuilder();
        StringBuilder strRefund = new StringBuilder();

        int iRes = 0;
        if (shiporderVO != null) {
            // 系统发货单主表信息插入数据库
            iRes = shiporderService.insertSelectiveShiporder(shiporderVO);
            if (iRes > 0) {
                logUtil.info(new DBLog(shiporderVO.getShiporderCode(), "系统手动分派生成发货单", "", "系统手动生成发货单"));
                int iResSku = 0;
                // 系统发货单商品明细
                List<ShiporderSkuVO> shiporderSkuList = shiporderVO.getShiporderSkuList();

                // 检索一遍订单非虚拟商品未分派的商品个数
                OrderSkuVO orderSkuVO = new OrderSkuVO();
                orderSkuVO.setOrderId(orderId);
                orderSkuVO.setIsVirt("n");
                orderSkuVO.setDeleted("n");
                List<OrderSkuVO> OrderSkuNotAllotList = orderSkuDAO.getOrderSkuListForNotAllot(orderSkuVO);

                boolean isall = true;
                for (int shiporderSkuIndex = 0; shiporderSkuIndex < shiporderSkuList.size(); shiporderSkuIndex++) {
                    iResSku = 0;
                    ShiporderSkuVO shiporderSku = shiporderSkuList.get(shiporderSkuIndex);
                    // 系统发货单商品明细信息插入数据库
                    iResSku = shiporderService.insertSelectiveShiporderSku(shiporderSku);
                    if (iResSku > 0 && !"0".equals(shiporderSku.getQty())) {
                        // 更新订单商品明细中的发货中数量
                        OrderSkuVO voparam = new OrderSkuVO();
                        voparam.setOrderSkuId(shiporderSku.getOrderSkuId());
                        OrderSkuVO sysOrderGoods = orderSkuDAO.getOrderSkuList(voparam).get(0);
                        if (StringUtils.isNotBlank(shiporderSku.getQty()) && StringUtils.isNumeric(shiporderSku.getQty())) {
                            if (sysOrderGoods.getShippingQty() != null) {
                                sysOrderGoods.setShippingQty(sysOrderGoods.getShippingQty() + Integer.valueOf(shiporderSku.getQty()));
                            } else {
                                sysOrderGoods.setShippingQty(Integer.valueOf(shiporderSku.getQty()));
                            }
                        }
                        sysOrderGoods.setUpdateTime(new Date());
                        int qty = sysOrderGoods.getQty() != null ? sysOrderGoods.getQty() : 0;
                        int shipedQty = sysOrderGoods.getShipedQty() != null ? sysOrderGoods.getShipedQty() : 0;
                        int shippingQty = sysOrderGoods.getShippingQty() != null ? sysOrderGoods.getShippingQty() : 0;
                        if (qty != shipedQty + shippingQty) {
                            isall = false;
                        }
                        orderSkuDAO.update(sysOrderGoods);

                        // 更新已分派数并记录库存变更日志
                        StockVO stockVO = new StockVO();
                        stockVO.setEntId(shiporderVO.getEntId());
                        stockVO.setStorId(shiporderVO.getStorId());
                        stockVO.setSkuId(shiporderSku.getSkuId());
                        if (StringUtils.isNotBlank(shiporderSku.getQty()) && StringUtils.isNumeric(shiporderSku.getQty())) {
                            stockVO.setAllotQty(Integer.valueOf(shiporderSku.getQty()));
                        }
                        stockVO.setSourceCode(shiporderVO.getShiporderCode());
                        stockVO.setTag("系统手动生成发货单");
                        stockService.updateStock(stockVO);
                    }
                }

                if (isall && shiporderVO.getOrderSkuNum() == shiporderSkuList.size()
                        && OrderSkuNotAllotList.size() == shiporderSkuList.size()) {
                    // OrderVO vo = orderDAO.findById(orderId);
                    OrderVO vo = new OrderVO();
                    vo.setOrderId(orderId);
                    vo.setOrderStatus("k");
                    // vo.setOperStus("al");//分派完成
                    vo.setUpdateTime(new Date());
                    orderDAO.update(vo);
                }
            }
        }
        returnMap.put("success", "y");
        return returnMap;
    }

    /**
     * 订单合并：
     * <p>
     * 合并的条件：当一条以上的订单为同网店、同客户ID、同收货人、同收货地址，系统判断这些订单如果网店的订单合并开关开启，订单状态为待审核未废弃，
     * 未合并过，未被锁定、 自动状态、不存在售后单据、不存在未废弃的发票、未在待审核队列中，那么系统进行自动合并，
     * 合并时仅合并新下载到系统的订单与系统中已存在且未合并的多条订单。 合并的处理如下：合并来源单号、买家留言、卖家备注和各种金额。
     * <p>
     * 合并后处理：更新子订单合并状态及合并后的GUID；删除合并前所有子订单中赠品；生成合并订单以及订单商品明细（主订单信息为拍单时间最早的订单为准，
     * 例拍单时间、付款 时间等）
     *
     * @param orderIdList 系统订单id列表
     */
    public String mergeOrder(List<String> orderIdList) {
        return "";
    }

    /**
     * 修改系统订单
     *
     * @param order 系统订单VO
     */
    public String updateOrder(OrderVO order) {
        return "";
    }

    /**
     * 创建系统订单
     *
     * @param order 系统订单VO
     */
    public String createOrder(OrderVO order) {
        return "";
    }

    /**
     * 检查订单问题 1.订单问题：如果订单存在以下情况会被拦截为订单问题单
     * 所属网店开启了自动合并订单，系统中存在可与之合并（同网店、同客户ID、同收货人、同收货地址）的已审核状态但不可操作的订单；
     * 有买家留言（网店开启了“有买家留言”拦截为订单问题）； 有卖家备注（网店开启了“有卖家备注”拦截为订单问题）；
     * 收货地址超长（网店开启了“收货地址超过N个字节拦截为订单问题）； 存在未废弃退款单； 系统状态和平台状态不一致（仅淘宝）
     * 合并订单的原订单数量大于15； 收货人、手机、电话信息有为空的； 身份证号为空（网店开启了“验证身份证号码“）；
     *
     * @param order 系统订单VO
     */
    public Map<String, Object> validateOrderProblems(OrderVO order) {
        return null;
    }

    /**
     * 自动审核分派 根据设置进行审核分派：按网店设置订单下载多长时间以后才能进行自动审核这个参数
     *
     * @param startTime 开始时间
     * @param endTime   结束时间
     */
    public String autoVerifyAndAssignOrder(Date startTime, Date endTime) {
        return "";
    }

    /**
     * 订单自动分派的逻辑： 自动审核成功的订单如果商品明细全部为虚拟商品，订单状态变为待分派，且打成手动状态；
     * 如果商品明细中存在非虚拟商品，系统自动做以下操作： 1.自动创建发票（订单需要开发票，且不存在未废弃发票）；
     * 2.生成出库单：以订单发货仓库、收货人、收货地址、非虚拟商品明细、订购数量等信息生待发货状态的订单出库单。
     * <p>
     * 订单自动审核分派成功，状态变为发货中。
     *
     * @param orderId 系统订单id
     */
    public String autoAssignOrder(String orderId) {
        return "";
    }

    /**
     * 生成系统订单
     *
     * @param ecTradeId 平台订单id
     */
    public String manualGenerateOrder(String ecTradeId) {
        return "";
    }

    /**
     * 废弃系统订单
     * 选中一条或多条订单，操作废弃，如果可以废弃要提示“废弃订单系统将无法继续处理，将可能导致漏发，确认废弃吗？”，并且要输入废弃原因（文本）。废弃成功
     * ，订单变为已废 弃状态。如果订单已不存在（被取消合并）、已归档、已废弃、自动处理、状态不是待审核的，不能被废弃。
     *
     * @param orderId
     * @param cancelRemark
     * @param strType      y:废弃，n:取消废弃
     * @return
     * @throws Exception
     */
    public Map<String, Object> abandonOrder(String orderId, String cancelRemark, String strType) throws Exception {
        Map<String, Object> returnMap = new HashMap<String, Object>();
        if (StringUtils.isNotBlank(orderId)) {
            String[] temp = orderId.split(",");
            if (temp.length > 0) {
                int result = 0;
                StringBuilder errmsg = new StringBuilder();
                for (int i = 0; i < temp.length; i++) {
                    OrderVO orderVO = orderDAO.findById(temp[i]);
                    orderVO.setIsCancel(strType);
                    if ("y".equals(strType)) {
                        orderVO.setCancelRemark(cancelRemark);
                    }

                    if ("au".equals(orderVO.getOperStus())) {
                        errmsg.append("订单编号：" + orderVO.getOrderCode() + "订单是自动状态的订单。n");
                    } else {
                        result = result + orderDAO.update(orderVO);
                    }

                }
                if (StringUtils.isBlank(errmsg.toString())) {
                    returnMap.put("result", "success");
                    returnMap.put("msg", "");
                } else {
                    returnMap.put("result", "failed");
                    returnMap.put("msg", errmsg.toString());
                }
                return returnMap;
            } else {
                returnMap.put("result", "failed");
                returnMap.put("msg", "没有选择数据");
                return returnMap;
            }

        } else {
            returnMap.put("result", "failed");
            returnMap.put("msg", "没有选择数据");
            return returnMap;
        }
    }

    /**
     * 查询系统订单（带分页）
     *
     * @param param 系统订单VO
     */
    public PageInfo<OrderVO> getOrdersPaged(OrderVO param) {
        return null;
    }

    /**
     * 查询系统订单（无分页）
     *
     * @param param
     */
    public List<OrderVO> getOrders(OrderVO param) {
        return null;
    }

    /**
     * 取消合并： 可以操作取消合并的订单要满足的条件有：已合并、未锁定的待审核且未废弃状态的订单；未建立售后事件、售后单据及有效发票；订单未全额退款。
     * 只能选择一条符合条件的订单操作取消合并，通过校验条件系统会将订单拆分恢复为合并前的多条订单，未通过校验的要有具体提示。所有订单记录日志。
     *
     * @param orderId 系统订单id
     */
    public Map<String, Object> cancelMerger(String orderId) throws Exception {
        Map<String, Object> returnMap = new HashMap<String, Object>();
        if (StringUtils.isNotBlank(orderId)) {
            int result = 0;
            StringBuilder msg = new StringBuilder();
            OrderVO orderVO = orderDAO.findById(orderId);
            if (StringUtils.isBlank(msg.toString()) && orderVO == null) {
                msg.append("数据不存在，不允许取消合并\\n");
            }
            // 取消合并按钮可见：【待审核】
            if (StringUtils.isBlank(msg.toString()) && !"a".equals(orderVO.getOrderStatus())) {
                msg.append(orderVO.getOrderCode() + " 不符合[待审核]条件，不允许取消合并\\n");
            }

            // 取消合并按钮可操作：合并订单、非自动状态，非锁定状态
            if (StringUtils.isBlank(msg.toString()) && !"c".equals(orderVO.getCombStus())) {
                msg.append(orderVO.getOrderCode() + " 不是合并订单，不允许取消合并\\n");
            }
            if (StringUtils.isBlank(msg.toString()) && "au".equals(orderVO.getOperStus())) {
                msg.append(orderVO.getOrderCode() + " 是自动状态，不允许取消合并\\n");
            }
            if (StringUtils.isBlank(msg.toString()) && "y".equals(orderVO.getIsLock())) {
                msg.append(orderVO.getOrderCode() + " 是锁定状态，不允许取消合并\\n");
            }

            // 合并后的订单存在售后事件，不能取消合并
            if (StringUtils.isBlank(msg.toString()) && null != afterSaleEventService.queryEventByOrderId(orderId)) {
                msg.append(orderVO.getOrderCode() + " 合并后的订单存在售后事件，不能取消合并\\n");
            }

            // 合并后的订单存在退款单，不能取消合并
            Map<String, String> mapRefund = new HashMap<String, String>();
            mapRefund.put("orderId", orderId);
            // mapRefund.put("isCancel", "n");
            mapRefund.put("deleted", "n");
            List<SysRefund> listSysRefund = sysRefundService.findSysRefundList(mapRefund);
            if (StringUtils.isBlank(msg.toString()) && listSysRefund != null && listSysRefund.size() > 0) {
                msg.append(orderVO.getOrderCode() + " 合并后的订单存在退款单，不能取消合并\\n");
            }

            // 合并后的订单存在退货单，不能取消合并
            SysReturnVO sysReturn = new SysReturnVO();
            sysReturn.setSourceId(orderId);
            sysReturn.setDeleted("n");
            // sysReturn.setIsCancel("n");
            List<SysReturnVO> listReturn = sysReturnService.querySysReturnVOList(sysReturn);
            if (StringUtils.isBlank(msg.toString()) && listReturn != null && listReturn.size() > 0) {
                msg.append(orderVO.getOrderCode() + " 合并后的订单存在退货单，不能取消合并\\n");
            }

            // 查找合并前的数据
            OrderVO voP = new OrderVO();
            voP.setForderId(orderVO.getOrderId());
            PageInfo<OrderVO> orderVOList = findPage(0, Integer.MAX_VALUE, "selectCombSource", voP);
            boolean flg = true;
            if (orderVOList != null && orderVOList.getList() != null && orderVOList.getList().size() > 0) {
                for (int index = 0; index < orderVOList.getList().size(); index++) {
                    OrderVO voU = orderVOList.getList().get(index);
                    OrderSkuVO orderSkuVO = new OrderSkuVO();
                    orderSkuVO.setOrderId(voU.getOrderId());
                    orderSkuVO.setDeleted("n");
                    List<OrderSkuVO> listOrderSku = orderSkuDAO.getOrderSkuList(orderSkuVO);
                    boolean hasNotGift = false;
                    if (listOrderSku != null && listOrderSku.size() > 0) {
                        for (int skuIndex = 0; skuIndex < listOrderSku.size(); skuIndex++) {
                            OrderSkuVO voSku = listOrderSku.get(skuIndex);
                            if ("n".equals(voSku.getIsGift())) {
                                hasNotGift = true;
                                break;
                            }
                        }
                    }
                    if (!hasNotGift) {
                        flg = false;
                        break;
                    }
                }
            }

            if (!flg) {
                msg.append(orderVO.getOrderCode() + " 合并前的订单已经不存在非赠品商品，无法取消合并\\n");
            }

            if (StringUtils.isBlank(msg.toString())) {
                orderVO.setDeleted("y");
                orderVO.setUpdateTime(new Date());

                SimpleDateFormat sdfTradeCode = new SimpleDateFormat("yyyyMMddHHmmss");
                String tradeCodeDelete = sdfTradeCode.format(new Date());
                orderVO.setTradeCode(orderVO.getTradeCode() + "-" + tradeCodeDelete);

                result = result + orderDAO.update(orderVO);

                if (orderVOList != null && orderVOList.getList() != null && orderVOList.getList().size() > 0) {
                    for (int index = 0; index < orderVOList.getList().size(); index++) {
                        OrderVO voU = orderVOList.getList().get(index);
                        voU.setCombStus("n");
                        voU.setForderId("");
                        voU.setOperStus("ma");
                        voU.setUpdateTime(new Date());
                        orderDAO.update(voU);
                    }
                }
            }

            returnMap.put("result", "success");
            returnMap.put("data", result);
            returnMap.put("msg", msg.toString());
            return returnMap;

        } else {
            returnMap.put("result", "success");
            returnMap.put("data", 0);
            return returnMap;
        }
    }

    /**
     * 手动审核分派
     *
     * @param orderId 系统订单id
     */
    public String manualVerifyAndAssignOrder(String orderId) {
        return "";
    }

    /**
     * 取消审核
     */
    public Map<String, Object> unAuditOrder(String orderId) throws Exception {
        Map<String, Object> returnMap = new HashMap<String, Object>();
        StringBuilder strIsAuto = new StringBuilder(); // 待分派，非自动状态下 可以操作取消审核操作。
        StringBuilder str = new StringBuilder(); // 有未取消的发货单

        if (StringUtils.isNotBlank(orderId)) {
            String[] temp = orderId.split(",");
            if (temp.length > 0) {
                int ibs = 0;
                for (int i = 0; i < temp.length; i++) {
                    ibs = 0;
                    OrderVO orderVO = orderDAO.findById(temp[i]);
                    if (!"i".equals(orderVO.getOrderStatus())) {
                        strIsAuto.append("订单编码：" + orderVO.getOrderCode() + " 该订单非待分派状态，取消审核失败\\n");
                        continue;
                    }

                    if ("au".equals(orderVO.getOperStus())) {
                        strIsAuto.append("订单编码：" + orderVO.getOrderCode() + " 该订单为自动状态，取消审核失败\\n");
                        continue;
                    }

                    ShiporderVO shiporderVO = new ShiporderVO();
                    shiporderVO.setSourceId(orderVO.getOrderId());
                    shiporderVO.setSourceType("or");
                    List<ShiporderVO> list = shiporderService.getShiporderList(shiporderVO);
                    if (list != null && list.size() > 0) {
                        for (int j = 0; j < list.size(); j++) {
                            if (!"y".equals(list.get(j).getCancelStatus())) {
                                str.append("订单编码：" + orderVO.getOrderCode() + " 有未取消的发货单\\n");
                                ibs = 1;
                                break;
                            }
                        }
                    }

                    if (ibs == 0) {
                        orderVO.setOrderStatus("a");
                        orderVO.setUpdateTime(new Date());
                        orderDAO.update(orderVO);
                    }
                }
            } else {
                str.append("请选择数据.");
            }
        } else {
            str.append("请选择数据");
        }
        if (StringUtils.isBlank(strIsAuto.toString() + str.toString())) {
            returnMap.put("result", "success");
        } else {
            returnMap.put("result", "faile");
        }
        returnMap.put("msg", strIsAuto.toString() + str.toString());
        return returnMap;
    }

    /**
     * 审核订单
     *
     * @param orderId 系统订单id
     */
    public Map<String, Object> verifyOrder(String orderId, String qAuditOrder) throws Exception {
        Map<String, Object> returnMap = new HashMap<String, Object>();
        StringBuilder strDifferentShop = new StringBuilder(); // 批选的订单必须在同一个网店下，有不同网店，则提示【所选订单不在同网店下，不能批量审核】
        StringBuilder strLock = new StringBuilder(); // 已锁定,不能审核
        StringBuilder strAuto = new StringBuilder(); // 自动状态,不能审核
        StringBuilder strBuyerNull = new StringBuilder(); // 客户ID为空，不能审核
        StringBuilder strSonOrderOver = new StringBuilder(); // 下订单的子订单数目大于15条，不能审核
        StringBuilder strStorNull = new StringBuilder(); // 没有指派发货仓库，不能审核
        StringBuilder strLgstNull = new StringBuilder(); // 没有指派物流公司，不能审核
        StringBuilder strAllGift = new StringBuilder(); // 没有非赠品商品明细，不能审核
        StringBuilder strCombine = new StringBuilder(); // 已被合并，不能审核
        StringBuilder strGoodsNull = new StringBuilder(); // 平台商品未关联系统商品，不能审核
        StringBuilder strOtherOrder = new StringBuilder(); // 以下订单的顾客还有其他未发货订单，是否对其审核？
        StringBuilder strVONull = new StringBuilder(); // 对象不存在
        StringBuilder strNoVerify = new StringBuilder(); // 对象不是待审核状态

        if (StringUtils.isNotBlank(orderId)) {
            String[] temp = orderId.split(",");
            if (temp.length > 0) {
                int result = 0;
                // StringBuilder msg = new StringBuilder();
                String shop = "";
                List<String> reDoIds = new ArrayList<String>();
                Map<String, OrderVO> okMap = new HashMap<String, OrderVO>();
                for (int i = 0; i < temp.length; i++) {
                    OrderVO orderVO = orderDAO.findById(temp[i]);
                    boolean flg = true;
                    // 对象不存在
                    if (orderVO == null || StringUtils.isBlank(temp[i])) {
                        strVONull.append(temp[i] + " 数据不存在\\n");
                        continue;
                    }

                    // 批选的订单必须在同一个网店下，有不同网店，则提示【所选订单不在同网店下，不能批量审核】
                    if (i == 0) {
                        shop = orderVO.getShopId();
                    } else {
                        if (!shop.equals(orderVO.getShopId())) {
                            strDifferentShop.append("所选订单不在同网店下，不能批量审核");
                            break;
                        }
                    }

                    // 以下订单的顾客还有其他未发货订单，是否对其审核？
                    if ("y".equals(qAuditOrder)) {
                        List<OrderVO> listVO = orderDAO.findOtherOrder(orderVO);
                        if (listVO.size() > 0) {
                            strOtherOrder.append(orderVO.getOrderCode() + " \\n");
                            reDoIds.add(temp[i]);
                            continue;
                        }
                    }

                    // 对象不是待审核状态
                    if (!"a".equals(orderVO.getOrderStatus())) {
                        strNoVerify.append(orderVO.getOrderCode() + "不符合[待审核]条件\\n");
                        flg = false;
                    }

                    // 已锁定,不能审核
                    if ("y".equals(orderVO.getIsLock())) {
                        strLock.append(orderVO.getOrderCode() + "已经锁定,审核失败\\n");
                        flg = false;
                    }

                    // 自动状态,不能审核
                    if ("au".equals(orderVO.getOperStus())) {
                        strAuto.append(orderVO.getOrderCode() + "是自动状态,审核失败\\n");
                        flg = false;
                    }

                    // 客户ID为空，不能审核
                    if (StringUtils.isBlank(orderVO.getBuyerNick())) {
                        strBuyerNull.append(orderVO.getOrderCode() + "客户ID为空,审核失败\\n");
                        flg = false;
                    }

                    // 下订单的子订单数目大于15条，不能审核
                    if (orderVO.getTradeCode().split(",").length > 15) {
                        strSonOrderOver.append(orderVO.getOrderCode() + "下订单的子订单数目大于15条,审核失败\\n");
                        flg = false;
                    }

                    // 没有指派发货仓库，不能审核
                    if (StringUtils.isBlank(orderVO.getStorId())) {
                        strStorNull.append(orderVO.getOrderCode() + "没有指派发货仓库,审核失败\\n");
                        flg = false;
                    }

                    // 没有指派物流公司，不能审核
                    if (StringUtils.isBlank(orderVO.getLgstId())) {
                        strLgstNull.append(orderVO.getOrderCode() + "没有指派物流公司,审核失败\\n");
                        flg = false;
                    }

                    // 已被合并，不能审核
                    if ("b".equals(orderVO.getCombStus())) {
                        strCombine.append(orderVO.getOrderCode() + "已被合并,审核失败\\n");
                        flg = false;
                    }

                    // 没有非赠品商品明细,不能审核 平台商品未关联系统商品,不能审核
                    OrderSkuVO vo = new OrderSkuVO();
                    vo.setOrderId(temp[i]);
                    vo.setDeleted("n");//如果orderSku的数据是删除状态就不进行审核
                    List<OrderSkuVO> arrSku = orderSkuDAO.getOrderSkuList(vo);
                    if (arrSku == null) {
                        flg = false;
                    } else {
                        boolean isNoGift = false;
                        boolean isSysGoods = true;
                        for (int j = 0; j < arrSku.size(); j++) {
                            if (!"y".equals(arrSku.get(j).getIsGift())) {
                                isNoGift = true;
                            }
                            if (StringUtils.isBlank(arrSku.get(j).getSkuId())) {
                                isSysGoods = false;
                            	// 更新orderSku的sku信息
                                if (!StringUtils.isBlank(arrSku.get(j).getEcSkuId())
                                		&& !StringUtils.isBlank(arrSku.get(j).getEcItemId())) {
                                    // 查询oms_ec_sku信息（ec_suk_id，ec_item_id）
                                	//if (StringUtils.isBlank(xxx.getSkuId())) {
                                	// 更新
                                	SkuVO skuVO=new SkuVO();
                                	skuVO.setEcSkuId(arrSku.get(j).getEcSkuId());
                                	skuVO.setEcItemId(arrSku.get(j).getEcItemId());
                                	List<SkuVO> skuVOList=itemService.findByWhere(skuVO);
                                	if(skuVOList.size()>0) {
                                		arrSku.get(j).setSkuId(skuVOList.get(0).getSkuId());
                                		arrSku.get(j).setSkuCode(skuVOList.get(0).getSkuCode());
                                		arrSku.get(j).setSkuName(skuVOList.get(0).getSkuName());
                                		arrSku.get(j).setGoodsId(skuVOList.get(0).getGoodsId());
                                		arrSku.get(j).setGoodsCode(skuVOList.get(0).getGoodsCode());
                                		arrSku.get(j).setGoodsName(skuVOList.get(0).getGoodsName());
                                		orderSkuDAO.update(arrSku.get(j));
                                		isSysGoods = true;
                                	}
                                }
                            }
                        }

                        if (!isNoGift) {
                            strAllGift.append(orderVO.getOrderCode() + "没有非赠品商品明细,审核失败\\n");
                            flg = false;
                        }

                        if (!isSysGoods) {
                            strGoodsNull.append(orderVO.getOrderCode() + "平台商品未关联系统商品,审核失败\\n");
                            flg = false;
                        }
                    }

                    if (flg) {
                        okMap.put(temp[i], orderVO);
                    }
                }

                if (StringUtils.isNotBlank(strDifferentShop.toString())) {
                    returnMap.put("result", "success");
                    returnMap.put("data", result);
                    returnMap.put("msg", strDifferentShop.toString());
                    returnMap.put("confirmMsg", "");
                } else {
                    for (Map.Entry<String, OrderVO> entry : okMap.entrySet()) {
                        OrderVO vo = entry.getValue();
                        vo.setOrderId(entry.getKey());
                        vo.setOrderStatus("i");
                        vo.setUpdateTime(new Date());
//                        vo.setFinishTime(new Date());
                        result = result + orderDAO.update(vo);
                    }

                    returnMap.put("result", "success");
                    returnMap.put("data", reDoIds);
                    returnMap.put("msg",
                            strLock.toString() + strAuto.toString() + strBuyerNull.toString() + strSonOrderOver.toString()
                                    + strStorNull.toString() + strLgstNull.toString() + strAllGift.toString() + strCombine.toString()
                                    + strGoodsNull.toString() + strNoVerify.toString());
                    if (StringUtils.isNotBlank(strOtherOrder.toString())) {
                        returnMap.put("confirmMsg", "该订单的顾客还有其他待审核的订单，是否对该审核？\\n" + strOtherOrder.toString());
                    } else {
                        returnMap.put("confirmMsg", "");
                    }
                }

                return returnMap;
            } else {
                returnMap.put("result", "success");
                returnMap.put("data", null);
                return returnMap;
            }

        } else {
            returnMap.put("result", "success");
            returnMap.put("data", 0);
            return returnMap;
        }
    }

    /**
     * 完成订单，选择一条或多条订单，操作完成。只有已发货商品且未被锁定、未废弃的已审核的订单可以被完成，如果校验未通过要提示出完成**条订单，
     * 以下订单无法完成，提示出 原因列表。 订单完成状态变为已完成。
     *
     * @param orderId 系统订单id
     */
    public Map<String, Object> finishOrder(String orderId) throws Exception {
        Map<String, Object> returnMap = new HashMap<String, Object>();
        if (StringUtils.isNotBlank(orderId)) {
            String[] temp = orderId.split(",");
            if (temp.length > 0) {
                int result = 0;
                StringBuilder msg = new StringBuilder();
                for (int i = 0; i < temp.length; i++) {
                    OrderVO orderVOFind = orderDAO.findById(temp[i]);
                    // 2017-12-11 李明修改
                    if (("r".equals(orderVOFind.getOrderStatus()) && "n".equals(orderVOFind.getIsLock()))) {
                            //&& ("商城".equals(orderVOFind.getShopType()))) {
                        OrderVO orderVO = new OrderVO();
                        orderVO.setOrderId(temp[i]);
                        orderVO.setOrderStatus("z");
                        orderVO.setFinishTime(new Date());
                        result = result + orderDAO.update(orderVO);
                        msg.append(orderVOFind.getOrderCode() + "完成<br/>");
                    } else {
                        msg.append(orderVOFind.getOrderCode() + "完成失败，不符合完成条件<br/>");
                    }
                }
                returnMap.put("result", "success");
                returnMap.put("data", result);
                returnMap.put("msg", msg.toString());
                return returnMap;
            } else {
                returnMap.put("result", "success");
                returnMap.put("data", 0);
                return returnMap;
            }

        } else {
            returnMap.put("result", "success");
            returnMap.put("data", 0);
            return returnMap;
        }
    }

    public Map<String, String> checkOffLockOrders(String orderId) throws Exception {
        Map<String, String> returnMap = new HashMap<String, String>();
        String id = "";
        StringBuilder msg = new StringBuilder();
        if (StringUtils.isNotBlank(orderId)) {
            String[] temp = orderId.split(",");
            if (temp.length > 0) {
                for (int j = 0; j < temp.length; j++) {
                    Map<String, String> mapRefund = new HashMap<String, String>();
                    mapRefund.put("orderId", temp[j]);
                    mapRefund.put("deleted", "n");

                    OrderVO orderVO = orderDAO.findById(temp[j]);

                    List<SysRefund> listSysRefund = sysRefundService.findSysRefundList(mapRefund);
                    if (listSysRefund != null && listSysRefund.size() > 0) {
                        for (int i = 0; i < listSysRefund.size(); i++) {
                            if ("k".equals(orderVO.getOrderStatus())) {
                                // 发货中也可以解锁，并需要判断是否存在 未废弃的退款单 有则给提示是否可以解锁？
                                if ("n".equals(listSysRefund.get(i).getIsCancel())) {
                                    msg.append("订单编号：" + orderVO.getOrderCode() + "存在未废弃的退款单，是否继续解锁？\\n");
                                    if (i == 0) {
                                        id = temp[j];
                                    } else {
                                        id = id + "," + temp[j];
                                    }
                                    break;
                                }
                            } else {
                                if ("n".equals(listSysRefund.get(i).getIsCancel())
                                        || (!"ec_closed".equalsIgnoreCase(listSysRefund.get(i).getEcRefundStatus())
                                        && !"ec_success".equalsIgnoreCase(listSysRefund.get(i).getEcRefundStatus()))) {
                                    msg.append("订单编号：" + orderVO.getOrderCode() + "存在未废弃或者未完成的退款单，是否继续解锁？\\n");
                                    if (i == 0) {
                                        id = temp[j];
                                    } else {
                                        id = id + "," + temp[j];
                                    }
                                    break;
                                }
                            }
                        }
                    }
                }
            }
        }

        returnMap.put("msg", msg.toString());
        returnMap.put("data", id);
        return returnMap;
    }

    /**
     * 锁定订单
     *
     * @param orderId 系统订单id
     */
    public Map<String, Object> lockOrders(String orderId) throws Exception {
        Map<String, Object> returnMap = new HashMap<String, Object>();

        CurrentUser currentUser = WebContextFactory.getWebContext().getCurrentUser();
        String currentUserName = currentUser.getFullName();

        if (StringUtils.isNotBlank(orderId)) {
            String[] temp = orderId.split(",");
            if (temp.length > 0) {
                int result = 0;
                boolean flg = true;
                StringBuilder errmsg = new StringBuilder();
                for (int i = 0; i < temp.length; i++) {
                    OrderVO orderVO = orderDAO.findById(temp[i]);
                    if (("a".equals(orderVO.getOrderStatus()) || "i".equals(orderVO.getOrderStatus())
                            || "k".equals(orderVO.getOrderStatus())) && "n".equals(orderVO.getIsLock())
                            && "ma".equals(orderVO.getOperStus())) {
                        // 更新订单状态
                        orderVO.setIsLock("y");
                        orderVO.setOperStus("lo");
                        orderVO.setUpdateTime(new Date());
                        orderVO.setLockTime(new Date());
                        orderVO.setLockUserName(currentUserName);
                        orderVO.setOrderId(temp[i]);
                        int iResOrder = orderDAO.update(orderVO);
                        result = result + iResOrder;
                        if (iResOrder > 0) {
                            // order下的发货单锁定，拿走的取消，没有拿走的锁定
                            shiporderService.lock(temp[i]);
                        }
                    } else {
                        flg = false;
                        errmsg.append("订单编号：" + orderVO.getOrderCode() + "不满足【待审核、待分派和发货中，且不是锁定的，手动状态数据】条件\\n");
                    }
                }
                if (!flg) {
                    returnMap.put("result", "failed");
                    returnMap.put("msg", errmsg.toString());

                } else {
                    returnMap.put("result", "success");
                    returnMap.put("msg", "");
                    returnMap.put("question", "");
                    returnMap.put("questionId", "");
                }
                return returnMap;
            } else {
                returnMap.put("result", "failed");
                returnMap.put("msg", "请选择要处理的数据");
                returnMap.put("question", "");
                returnMap.put("questionId", "");
                return returnMap;
            }
        } else {
            returnMap.put("result", "failed");
            returnMap.put("msg", "请选择要处理的数据");
            returnMap.put("question", "");
            returnMap.put("questionId", "");
            return returnMap;
        }
    }

    /**
     * 解锁订单
     *
     * @param orderId 系统订单id
     */
    public Map<String, Object> unlockOrders(String orderId) throws Exception {
        Map<String, Object> returnMap = new HashMap<String, Object>();
        if (StringUtils.isNotBlank(orderId)) {
            String[] temp = orderId.split(",");
            if (temp.length > 0) {
                int result = 0;
                boolean flg = true;
                StringBuilder errmsg = new StringBuilder();
                for (int i = 0; i < temp.length; i++) {
                    OrderVO orderVO = orderDAO.findById(temp[i]);
                    if (("a".equals(orderVO.getOrderStatus()) || "i".equals(orderVO.getOrderStatus())
                            || "k".equals(orderVO.getOrderStatus())) && "y".equals(orderVO.getIsLock())) {
                        orderVO.setIsLock("n");
                        orderVO.setOperStus("ma");
                        orderVO.setUpdateTime(new Date());
                        orderVO.setOrderId(temp[i]);
                        int iResOrder = orderDAO.update(orderVO);
                        result = result + iResOrder;

                        if (iResOrder > 0) {
                            // order下解锁待发货的发货单 ，发货中的发货单不做处理
                            shiporderService.unLock(temp[i]);
                        }

                    } else if ("n".equals(orderVO.getIsLock())) {
                        flg = false;
                        errmsg.append("订单编号：" + orderVO.getOrderCode() + "为非锁定状态，无需解锁\\n");
                    } else {
                        flg = false;
                        errmsg.append("订单编号：" + orderVO.getOrderCode() + "不满足【待审核,待分派,发货中,且是锁定】条件\\n");
                    }
                }
                if (!flg) {
                    returnMap.put("result", "failed");
                    returnMap.put("msg", errmsg.toString());
                } else {
                    returnMap.put("result", "success");
                    returnMap.put("msg", "");
                    returnMap.put("data", "解锁成功");
                }
                return returnMap;
            } else {
                returnMap.put("result", "failed");
                returnMap.put("msg", "请选择要处理的数据");
                return returnMap;
            }
        } else {
            returnMap.put("result", "failed");
            returnMap.put("msg", "请选择要处理的数据");
            return returnMap;
        }
    }

    /**
     * 设置为自动订单
     *
     * @param orderId 系统订单id
     */
    public Map<String, Object> setOrderAutomatically(String orderId) throws Exception {
        Map<String, Object> returnMap = new HashMap<String, Object>();
        if (StringUtils.isNotBlank(orderId)) {
            String[] temp = orderId.split(",");
            if (temp.length > 0) {
                int result = 0;
                boolean flg = true;
                StringBuilder errmsg = new StringBuilder();
                for (int i = 0; i < temp.length; i++) {
                    OrderVO orderVO = orderDAO.findById(temp[i]);
                    if (("a".equals(orderVO.getOrderStatus())) && !"au".equals(orderVO.getOperStus())) {
                        orderVO.setOperStus("au");
                        orderVO.setUpdateTime(new Date());
                        orderVO.setOrderId(temp[i]);
                        result = result + orderDAO.update(orderVO);
                    } else {
                        flg = false;
                        errmsg.append("订单编号：" + orderVO.getOrderCode() + "不满足【待审核且不是自动】条件\\n");
                    }

                }
                if (!flg) {
                    returnMap.put("result", "failed");
                    returnMap.put("msg", errmsg.toString());
                } else {
                    returnMap.put("result", "success");
                    returnMap.put("msg", "");
                }
                return returnMap;
            } else {
                returnMap.put("result", "failed");
                returnMap.put("msg", "请选择要处理的数据");
                return returnMap;
            }
        } else {
            returnMap.put("result", "failed");
            returnMap.put("msg", "请选择要处理的数据");
            return returnMap;
        }
    }

    /**
     * 设置为手动订单
     *
     * @param orderId 系统订单id
     */
    public Map<String, Object> setOrderManually(String orderId) throws Exception {
        Map<String, Object> returnMap = new HashMap<String, Object>();
        if (StringUtils.isNotBlank(orderId)) {
            String[] temp = orderId.split(",");
            if (temp.length > 0) {
                int result = 0;
                boolean flg = true;
                StringBuilder errmsg = new StringBuilder();
                for (int i = 0; i < temp.length; i++) {
                    OrderVO orderVO = orderDAO.findById(temp[i]);
                    if ((("a".equals(orderVO.getOrderStatus()) || "i".equals(orderVO.getOrderStatus())
                            || "k".equals(orderVO.getOrderStatus()))) && "n".equals(orderVO.getIsLock())) {
                        orderVO.setOperStus("ma");
                        orderVO.setUpdateTime(new Date());
                        orderVO.setOrderId(temp[i]);
                        result = result + orderDAO.update(orderVO);
                    } else {
                        flg = false;
                        errmsg.append("订单编号：" + orderVO.getOrderCode() + "不满足【待审核,待分派,发货中,且必须是解锁状态】条件\\n");
                    }

                }
                if (!flg) {
                    returnMap.put("result", "failed");
                    returnMap.put("msg", errmsg.toString());
                } else {
                    returnMap.put("result", "success");
                    returnMap.put("msg", "");
                }
                return returnMap;
            } else {
                returnMap.put("result", "failed");
                returnMap.put("msg", "请选择要处理的数据");
                return returnMap;
            }
        } else {
            returnMap.put("result", "failed");
            returnMap.put("msg", "请选择要处理的数据");
            return returnMap;
        }
    }

    /**
     * 恢复已删除订单商品
     * 修改待审核状态订单时，点击“恢复已删除商品”时，展示出之前已删除的该订单中商品明细（内容同订单明细），可以批量选择恢复至订单商品明细。
     *
     * @param orderId         系统订单id
     * @param orderItemIdList
     */
    public String withdrawDeletedOrders(String orderId, List<String> orderItemIdList) {
        return "";
    }

    /**
     * 申请取消出库 在订单发货信息tab中选择一条出库单，点击申请取消，判断出库单状态对应以下处理： 1.
     * 未进行任何操作（未录入快递单号、未打印快递单、未打印发货单），系统直接取消出库单（状态变为已取消），关联订单如果无其他未取消出库单，
     * 订单状态回滚至待审核； 2.
     * 出库单已操作或已系统发货或已平台发货，出库单标识申请取消，由库房操作是否同意取消；如果仓库反馈同意取消，系统取消该出库单（状态变为已取消），
     * 关联订单如果无其他未 取消出库单，订单状态回滚至待审核； 3.订单出库单已发货，不能申请取消；
     *
     * @param orderId    系统订单id
     * @param outBoundId
     */
    public String askForStopOutBound(String orderId, String outBoundId) {
        return "";
    }

    /**
     * 同意取消出库单，由仓库调用本接口 如果仓库反馈同意取消，系统取消该出库单（状态变为已取消），关联订单如果无其他未取消出库单，订单状态回滚至待审核；
     *
     * @param outBoundId
     */
    public String agreeStopOutBound(String outBoundId) {
        return "";
    }

    /**
     * 批量修改物流公司
     *
     */
    public int batchUpdateLogisticsCompany(String orderId, String lgstId, String lgstName, String lgstCode) throws Exception {
        if (StringUtils.isNotBlank(orderId)) {
            String[] temp = orderId.split(",");
            if (temp.length > 0) {
                int result = 0;
                boolean flg = true;
                for (int i = 0; i < temp.length; i++) {
                    OrderVO orderVO = new OrderVO();
                    if ("au".equals(orderDAO.findById(temp[i]).getOperStus())) {
                        flg = false;
                    } else {
                        orderVO.setOrderId(temp[i]);
                        orderVO.setLgstId(lgstId);
                        orderVO.setLgstName(lgstName);
                        orderVO.setLgstCode(lgstCode);
                        orderVO.setUpdateTime(new Date());
                        result = result + orderDAO.update(orderVO);
                    }

                }
                if (flg) {
                    return result;
                } else {
                    return -1;
                }

            } else {
                return 0;
            }

        } else {
            return 0;
        }
    }

    /**
     * 批量修改发货仓库
     *
     */
    public int batchUpdateShipmentWarehouse(String orderId, String storId, String storName, String storCode) throws Exception {
        if (StringUtils.isNotBlank(orderId)) {
            String[] temp = orderId.split(",");
            if (temp.length > 0) {
                int result = 0;
                boolean flg = true;
                for (int i = 0; i < temp.length; i++) {
                    OrderVO orderVO = new OrderVO();
                    if ("au".equals(orderDAO.findById(temp[i]).getOperStus())) {
                        flg = false;
                    } else {
                        orderVO.setOrderId(temp[i]);
                        orderVO.setStorId(storId);
                        orderVO.setStorCode(storCode);
                        orderVO.setStorName(storName);
                        orderVO.setUpdateTime(new Date());
                        result = result + orderDAO.update(orderVO);
                    }
                }
                if (flg) {
                    return result;
                } else {
                    return -1;
                }
            } else {
                return 0;
            }

        } else {
            return 0;
        }
    }

    /**
     * 批量修改内部备注
     *
     * @param memo        内部备注
     */
    public String batchUpdateOrderMemo(String orderId, String memo) throws Exception {
        StringBuffer stringBuffer = new StringBuffer();
        if (StringUtils.isNotBlank(orderId)) {
            String[] temp = orderId.split(",");
            if (temp.length > 0) {
                for (int i = 0; i < temp.length; i++) {
                    String result = updateOrderMemo(temp[i], memo);
                    stringBuffer.append(result + "<br/>");
                }
            }
        }
        return stringBuffer.toString();
    }

    /**
     * 单个修改内部备注
     *
     * @param orderId
     * @param memo
     * @return
     * @throws Exception
     */
    public String updateOrderMemo(String orderId, String memo) throws Exception {
        OrderVO orderFindVO = orderDAO.findById(orderId);
        if ("au".equalsIgnoreCase(orderFindVO.getOperStus())) {
            return orderFindVO.getOrderCode() + ":自动状态订单不能修改内部备注";
        } else {
            OrderVO orderVO = new OrderVO();
            orderVO.setOrderId(orderId);
            orderVO.setRemark(memo);
            orderVO.setUpdateTime(new Date());
            orderDAO.update(orderVO);
            return orderFindVO.getOrderCode() + ":修改完成";
        }
    }

    /**
     * 检测订单商品问题
     *
     * @param orderGoodsList
     */
    public Map<String, String> validateOrderGoodsProblems(List<OrderSku> orderGoodsList) {
        return null;
    }

    /**
     * 手动强制合并订单（暂时不做）
     *
     * @param orderIdList 要合并的订单id列表
     */
    public Map<String, Object> forceMergeOrdersManual(List<String> orderIdList) {
        return null;
    }

    /**
     * 验证手机号码（支持国际格式，+86135xxxx...（中国内地），+00852137xxxx...（中国香港））
     *
     * @param mobile 移动、联通、电信运营商的号码段
     *               <p>
     *               移动的号段：134(0-8)、135、136、137、138、139、147（预计用于TD上网卡）
     *               、150、151、152、157（TD专用）、158、159、187（未启用）、188（TD专用）
     *               </p>
     *               <p>
     *               联通的号段：130、131、132、155、156（世界风专用）、185（未启用）、186（3g）
     *               </p>
     *               <p>
     *               电信的号段：133、153、180（未启用）、189
     *               </p>
     * @return 验证成功返回true，验证失败返回false
     */
    private boolean isMobile(String mobile) {
        if (StringUtils.isBlank(mobile)) {
            return true;
        }
        String regex = "^((13[0-9])|(14[5|7])|(15([0-3]|[5-9]))|(18[0,5-9]))\\d{8}$";
        return Pattern.matches(regex, mobile);
    }

    /**
     * 区号+座机号码+分机号码
     *
     * @param fixedPhone
     * @return
     */
    private boolean isFixedPhone(String fixedPhone) {
        if (StringUtils.isBlank(fixedPhone)) {
            return true;
        }
        String reg = "^[0][1-9]{2,3}-[0-9]{5,10}$";
        return Pattern.matches(reg, fixedPhone);
    }

    public OrderVO getOrderInfoByTradeCode(String tradeCode) throws Exception {
        OrderVO orderData = null;
        OrderVO orderVO = new OrderVO();
        orderVO.setTradeCode(tradeCode);
        List<OrderVO> orderDataList = orderDAO.findByTradeCode(orderVO);
        if (orderDataList != null && orderDataList.size() > 0) {
            orderData = orderDataList.get(0);
        }

        return orderData;
    }

    /**
     * 系统订单画面VO检查
     *
     * @return
     */
    private Map<String, String> checkOrderInfo(OrderInfoVO orderInfo, Map<String, String> map) throws Exception {
        Map<String, String> result = new HashMap<String, String>();
        // GoodsInfoVO是空
        if (orderInfo == null) {
            result.put("isOk", "n");
            result.put("errormessage", "系统商品VO为空");
            return result;
        }

        if ("insert".equals(orderInfo.getAction())) {

            if (orderInfo.getOrder() == null) {
                result.put("isOk", "n");
                result.put("errormessage", "订单信息为空");
                return result;
            }
            Order order = orderInfo.getOrder();

            // 订单来源不能为空
            // if (StringUtils.isBlank(order.getShopType())) {
            // result.put("isOk", "n");
            // result.put("errormessage", "订单来源为空");
            // return result;
            // }

            // 来源单号不能为空
            if (StringUtils.isBlank(order.getTradeCode())) {
                result.put("isOk", "n");
                result.put("errormessage", "来源单号为空");
                return result;
            }

            // 订单类型不能为空
            if (StringUtils.isBlank(order.getOrderType())) {
                result.put("isOk", "n");
                result.put("errormessage", "订单类型为空");
                return result;
            }

            // 支付方式不能为空
            if (StringUtils.isBlank(order.getPayMode())) {
                result.put("isOk", "n");
                result.put("errormessage", "支付方式为空");
                return result;
            }

            // 客户ID不能为空
            if (StringUtils.isBlank(order.getBuyerNick())) {
                result.put("isOk", "n");
                result.put("errormessage", "客户ID为空");
                return result;
            }

            // 网店不能为空
            if (StringUtils.isBlank(order.getShopId())) {
                result.put("isOk", "n");
                result.put("errormessage", "网店为空");
                return result;
            }

            // 发货仓库不能为空
            if (StringUtils.isBlank(order.getStorId())) {
                result.put("isOk", "n");
                result.put("errormessage", "发货仓库为空");
                return result;
            }

            // 收货人不能为空
            if (StringUtils.isBlank(order.getCons())) {
                result.put("isOk", "n");
                result.put("errormessage", "收货人为空");
                return result;
            }

            // 收货人不能为空
            if (StringUtils.isBlank(order.getCons())) {
                result.put("isOk", "n");
                result.put("errormessage", "收货人为空");
                return result;
            }

            // 收货人地址不能为空
            if (StringUtils.isBlank(order.getConsAddr())) {
                result.put("isOk", "n");
                result.put("errormessage", "收货人地址为空");
                return result;
            }

            // 固定电话与手机至少要输入一个 手机
            if (StringUtils.isBlank(order.getConsTel()) && StringUtils.isBlank(order.getConsMobile())) {
                result.put("isOk", "n");
                result.put("errormessage", "固定电话与手机至少要输入一个 手机");
                return result;
            }

            // if (!isMobile(order.getConsMobile())) {
            // result.put("isOk", "n");
            // result.put("errormessage", "手机输入不正确");
            // return result;
            // }

            // if (!isFixedPhone(order.getConsTel())) {
            // result.put("isOk", "n");
            // result.put("errormessage", "固定电话输入不正确");
            // return result;
            // }

            // 对sku列表进行check
            if (orderInfo.getArrSku() == null || orderInfo.getArrSku().size() <= 0) {
                result.put("isOk", "n");
                result.put("errormessage", "商品信息列表不能为空,或者画面数据没有修改过");
                return result;
            }
            List<OrderSkuVO> listOrderSku = orderInfo.getArrSku();
            boolean isZeroFactUnitPrice = false;
            BigDecimal cash = BigDecimal.ZERO;
            for (int i = 0; i < listOrderSku.size(); i++) {
                OrderSkuVO vo = listOrderSku.get(i);
                if (StringUtils.isBlank(vo.getGoodsCode())) {
                    result.put("isOk", "n");
                    result.put("errormessage", "商品商家编码不能为空");
                    return result;
                }

                if (StringUtils.isBlank(vo.getGoodsName())) {
                    result.put("isOk", "n");
                    result.put("errormessage", "商品名称不能为空");
                    return result;
                }

                if (StringUtils.isBlank(vo.getSkuCode())) {
                    result.put("isOk", "n");
                    result.put("errormessage", "规格商家编码不能为空");
                    return result;
                }

                if (StringUtils.isBlank(vo.getSkuName())) {
                    result.put("isOk", "n");
                    result.put("errormessage", "规格名称不能为空");
                    return result;
                }

                if (vo.getQty() == null || vo.getQty().intValue() <= 0) {
                    result.put("isOk", "n");
                    result.put("errormessage", "订购数量不能为空或者小于零");
                    return result;
                }

                // 来源单号不允许重复
                OrderVO orderVO = new OrderVO();
                orderVO.setTradeCode(order.getTradeCode());
                if (StringUtils.isNotBlank(order.getShopType())){
                    orderVO.setShopType(order.getShopType());
                }

                List<OrderVO> listOrder = orderDAO.findByTradeCode(orderVO);
                if (listOrder != null && listOrder.size() > 0) {
                    result.put("isOk", "n");
                    result.put("errormessage", "来源单号已经存在");
                    return result;
                }

                // 该订单的商品中存在实际单价为0的商品，您确认要保存该订单信息吗？
                if (vo.getFactUnitPrice() == null || vo.getFactUnitPrice().compareTo(BigDecimal.ZERO) == 0) {
                    isZeroFactUnitPrice = true;
                    break;
                }

                // 您要新增订单的商品金额(实际金额之和)不为0而支付金额为0，您确认要保存该订单信息吗？
                cash = cash.add(vo.getFactUnitPrice().multiply(new BigDecimal(vo.getQty())));

            }

            if (isZeroFactUnitPrice && "y".equals(orderInfo.getCheckPrice())) {
                result.put("isOk", "q_Price");
                result.put("errormessage", "该订单的商品中存在实际单价为0的商品，您确认要保存该订单信息吗？");
                return result;
            }

            // 您要新增订单的商品金额(实际金额之和)不为0而支付金额为0，您确认要保存该订单信息吗？
            if ("y".equals(orderInfo.getCheckCash()) && cash.compareTo(BigDecimal.ZERO) > 0
                    && (order.getPaidFee() == null || order.getPaidFee().compareTo(BigDecimal.ZERO) == 0)) {
                result.put("isOk", "q_cash");
                result.put("errormessage", "您要新增订单的商品金额(实际金额之和)不为0而支付金额为0，您确认要保存该订单信息吗？");
                return result;
            }

        } else if ("update".equals(orderInfo.getAction())) {

            if (orderInfo.getOrder() != null) {
                Order order = orderInfo.getOrder();
                if (!"sku".equals(orderInfo.getType())) {
                    // 订单来源不能为空
                    // if (StringUtils.isBlank(order.getShopType())) {
                    // result.put("isOk", "n");
                    // result.put("errormessage", "订单来源为空");
                    // return result;
                    // }

                    // 来源单号不能为空
                    if (StringUtils.isBlank(order.getTradeCode())) {
                        result.put("isOk", "n");
                        result.put("errormessage", "来源单号为空");
                        return result;
                    }

                    // 订单类型不能为空
                    if (StringUtils.isBlank(order.getOrderType())) {
                        result.put("isOk", "n");
                        result.put("errormessage", "订单类型为空");
                        return result;
                    }

                    // 支付方式不能为空
                    if (StringUtils.isBlank(order.getPayMode())) {
                        result.put("isOk", "n");
                        result.put("errormessage", "支付方式为空");
                        return result;
                    }

                    // 客户ID不能为空
                    if (StringUtils.isBlank(order.getBuyerNick())) {
                        result.put("isOk", "n");
                        result.put("errormessage", "客户ID为空");
                        return result;
                    }

                    // 网店不能为空
                    if (StringUtils.isBlank(order.getShopId())) {
                        result.put("isOk", "n");
                        result.put("errormessage", "网店为空");
                        return result;
                    }

                    // 发货仓库不能为空
                    if (StringUtils.isBlank(order.getStorId())) {
                        result.put("isOk", "n");
                        result.put("errormessage", "发货仓库为空");
                        return result;
                    }

                    // 收货人不能为空
                    if (StringUtils.isBlank(order.getCons())) {
                        result.put("isOk", "n");
                        result.put("errormessage", "收货人为空");
                        return result;
                    }

                    // 收货人不能为空
                    if (StringUtils.isBlank(order.getCons())) {
                        result.put("isOk", "n");
                        result.put("errormessage", "收货人为空");
                        return result;
                    }

                    // 收货人地址不能为空
                    if (StringUtils.isBlank(order.getConsAddr())) {
                        result.put("isOk", "n");
                        result.put("errormessage", "收货人地址为空");
                        return result;
                    }

                    // 固定电话与手机至少要输入一个 手机
                    if (StringUtils.isBlank(order.getConsTel()) && StringUtils.isBlank(order.getConsMobile())) {
                        result.put("isOk", "n");
                        result.put("errormessage", "固定电话与手机至少要输入一个 手机");
                        return result;
                    }

                    // if (!isMobile(order.getConsMobile())) {
                    // result.put("isOk", "n");
                    // result.put("errormessage", "手机输入不正确");
                    // return result;
                    // }

                    // if (!isFixedPhone(order.getConsTel())) {
                    // result.put("isOk", "n");
                    // result.put("errormessage", "固定电话输入不正确");
                    // return result;
                    // }
                }
                // 对sku列表进行check
                if (orderInfo.getArrSku() == null || orderInfo.getArrSku().size() <= 0) {
                    result.put("isOk", "n");
                    result.put("errormessage", "商品信息列表不能为空");
                    return result;
                }

                // 对sku列表进行check
                if (orderInfo.getArrSku() != null || orderInfo.getArrSku().size() > 0) {

                    List<OrderSkuVO> listOrderSku = orderInfo.getArrSku();
                    for (int i = 0; i < listOrderSku.size(); i++) {
                        OrderSkuVO vo = listOrderSku.get(i);
                        if (!"y".equals(vo.getDeleted())) {// 不是删除的时候
                            if (!"sku".equals(orderInfo.getType())) {
                                if (StringUtils.isBlank(vo.getGoodsCode())) {
                                    result.put("isOk", "n");
                                    result.put("errormessage", "商品商家编码不能为空");
                                    return result;
                                }

                                if (StringUtils.isBlank(vo.getGoodsName())) {
                                    result.put("isOk", "n");
                                    result.put("errormessage", "商品名称不能为空");
                                    return result;
                                }

                                if (StringUtils.isBlank(vo.getSkuCode())) {
                                    result.put("isOk", "n");
                                    result.put("errormessage", "规格商家编码不能为空");
                                    return result;
                                }

                                if (StringUtils.isBlank(vo.getSkuName())) {
                                    result.put("isOk", "n");
                                    result.put("errormessage", "规格名称不能为空");
                                    return result;
                                }

                                if (vo.getQty() == null || vo.getQty().intValue() <= 0) {
                                    result.put("isOk", "n");
                                    result.put("errormessage", "订购数量不能为空或者小于零");
                                    return result;
                                }
                            }
                        } else {
                            OrderSkuVO voP = new OrderSkuVO();
                            voP.setOrderSkuId(vo.getOrderSkuId());
                            OrderSkuVO orderSkuVO = orderSkuDAO.getOrderSkuList(voP).get(0);
                            if (!orderSkuVO.getDeleted().equals(vo.getDeleted())) { // 当画面数据由非删除状态到删除状态的时候，也就是删除动作
                                if (!"sku".equals(orderInfo.getType()) && (vo.getQty() == null || vo.getQty().intValue() <= 0)) {
                                    result.put("isOk", "n");
                                    result.put("errormessage", "订购数量不能为空或者小于零");
                                    return result;
                                }

                                // 待分派订单删除商品操作 校验：
                                OrderVO orderVO = orderDAO.findById(orderSkuVO.getOrderId());
                                if ("y".equals(vo.getDeleted()) && "i".equals(orderVO.getOrderStatus())) {

                                    // if (listOrderSku.size() == 1) {
                                    // // 订单下只存在一件商品，不能删除订单上商品！
                                    // result.put("isOk", "n");
                                    // result.put("errormessage",
                                    // "订单下只存在一件商品，不能删除订单上商品！");
                                    // return result;
                                    // }

                                    // 判断当前删除商品的发货中数和已发货数，如果任意一个数大于0，则提示！
                                    if ((orderSkuVO.getShippingQty() != null && orderSkuVO.getShippingQty() > 0)
                                            || (orderSkuVO.getShipedQty() != null && orderSkuVO.getShipedQty() > 0)) {
                                        result.put("isOk", "n");
                                        result.put("errormessage", "订单下的该商品存在未取消的出库单，不能删除订单上商品！");
                                        return result;
                                    }
                                }
                            }
                        }
                    }
                }

            }

        }

        result.put("isOk", "y");
        result.put("errormessage", "");
        return result;
    }

    /**
     * 系统订单画面VO检查
     *
     * @return
     */
    private Map<String, String> checkOrderInfoImport(OrderInfoVO orderInfo, Map<String, String> map) throws Exception {
        Map<String, String> result = new HashMap<String, String>();
        // GoodsInfoVO是空
        if (orderInfo == null) {
            result.put("isOk", "n");
            result.put("errormessage", "系统商品VO为空");
            return result;
        }

        if ("insert".equals(orderInfo.getAction())) {

            if (orderInfo.getOrder() == null) {
                result.put("isOk", "n");
                result.put("errormessage", "订单信息为空");
                return result;
            }
            Order order = orderInfo.getOrder();

            // 订单来源不能为空
            // if (StringUtils.isBlank(order.getShopType())) {
            // result.put("isOk", "n");
            // result.put("errormessage", "订单来源为空");
            // return result;
            // }

            // 来源单号不能为空
            if (StringUtils.isBlank(order.getTradeCode())) {
                result.put("isOk", "n");
                result.put("errormessage", "来源单号为空");
                return result;
            }

            // 订单类型不能为空
            if (StringUtils.isBlank(order.getOrderType())) {
                result.put("isOk", "n");
                result.put("errormessage", "来源单号:"+order.getTradeCode()+"订单类型为空");
                return result;
            }

            // 支付方式不能为空
            if (StringUtils.isBlank(order.getPayMode())) {
                result.put("isOk", "n");
                result.put("errormessage", "来源单号:"+order.getTradeCode()+"支付方式为空");
                return result;
            }

            // 客户ID不能为空
            if (StringUtils.isBlank(order.getBuyerNick())) {
                result.put("isOk", "n");
                result.put("errormessage", "来源单号:"+order.getTradeCode()+"客户ID为空");
                return result;
            }

            // 网店不能为空
            if (StringUtils.isBlank(order.getShopName())) {
                result.put("isOk", "n");
                result.put("errormessage", "来源单号:"+order.getTradeCode()+"网店为空");
                return result;
            }

            // 发货仓库不能为空
            if (StringUtils.isBlank(order.getStorCode())) {
                result.put("isOk", "n");
                result.put("errormessage", "来源单号:"+order.getTradeCode()+"发货仓库为空");
                return result;
            }

//            // 收货人不能为空
//            if (StringUtils.isBlank(order.getCons())) {
//                result.put("isOk", "n");
//                result.put("errormessage", "来源单号:"+order.getTradeCode()+"收货人为空");
//                return result;
//            }

            // 收货人不能为空
            if (StringUtils.isBlank(order.getCons())) {
                result.put("isOk", "n");
                result.put("errormessage", "来源单号:"+order.getTradeCode()+"收货人为空");
                return result;
            }

            // 收货人地址不能为空
            if (StringUtils.isBlank(order.getConsAddr())) {
                result.put("isOk", "n");
                result.put("errormessage", "来源单号:"+order.getTradeCode()+"收货人地址为空");
                return result;
            }

            // 固定电话与手机至少要输入一个 手机
            if (StringUtils.isBlank(order.getConsTel()) && StringUtils.isBlank(order.getConsMobile())) {
                result.put("isOk", "n");
                result.put("errormessage", "来源单号:"+order.getTradeCode()+"固定电话与手机至少要输入一个 手机");
                return result;
            }

            // if (!isMobile(order.getConsMobile())) {
            // result.put("isOk", "n");
            // result.put("errormessage", "手机输入不正确");
            // return result;
            // }

            // if (!isFixedPhone(order.getConsTel())) {
            // result.put("isOk", "n");
            // result.put("errormessage", "固定电话输入不正确");
            // return result;
            // }

            // 对sku列表进行check
            if (orderInfo.getArrSku() == null || orderInfo.getArrSku().size() <= 0) {
                result.put("isOk", "n");
                result.put("errormessage", "来源单号:"+order.getTradeCode()+"商品信息列表不能为空,或者画面数据没有修改过");
                return result;
            }
            List<OrderSkuVO> listOrderSku = orderInfo.getArrSku();
            boolean isZeroFactUnitPrice = false;
            BigDecimal cash = BigDecimal.ZERO;
            for (int i = 0; i < listOrderSku.size(); i++) {
                OrderSkuVO vo = listOrderSku.get(i);
                GoodsSkuVO goodsSkuVO  = new GoodsSkuVO();
                goodsSkuVO.setSkuCode(vo.getSkuCode());
                goodsSkuVO.setEntId(map.get("entId"));
                List<GoodsSkuVO> goodsSkuVOList = findPage("selectGoodsSkuListBySkuCodeEntId", goodsSkuVO);

                if (goodsSkuVOList==null || goodsSkuVOList.size()<=0){
                    result.put("isOk", "n");
                    result.put("errormessage", "来源单号:"+order.getTradeCode()+"商品数据不存在");
                    return result;
                }

                if (StringUtils.isBlank(goodsSkuVOList.get(0).getGoodsCode())) {
                    result.put("isOk", "n");
                    result.put("errormessage", "来源单号:"+order.getTradeCode()+"商品商家编码不能为空");
                    return result;
                }

                if (StringUtils.isBlank(goodsSkuVOList.get(0).getGoodsName())) {
                    result.put("isOk", "n");
                    result.put("errormessage", "来源单号:"+order.getTradeCode()+"商品名称不能为空");
                    return result;
                }

                if (StringUtils.isBlank(goodsSkuVOList.get(0).getSkuCode())) {
                    result.put("isOk", "n");
                    result.put("errormessage", "来源单号:"+order.getTradeCode()+"规格商家编码不能为空");
                    return result;
                }

                if (StringUtils.isBlank(goodsSkuVOList.get(0).getSkuName())) {
                    result.put("isOk", "n");
                    result.put("errormessage", "来源单号:"+order.getTradeCode()+"规格名称不能为空");
                    return result;
                }

                if (vo.getQty() == null || vo.getQty().intValue() <= 0) {
                    result.put("isOk", "n");
                    result.put("errormessage", "来源单号:"+order.getTradeCode()+"订购数量不能为空或者小于零");
                    return result;
                }

                // 来源单号不允许重复
                OrderVO orderVO = new OrderVO();
                orderVO.setTradeCode(order.getTradeCode());
                if (StringUtils.isNotBlank(order.getShopType())){
                    orderVO.setShopType(order.getShopType());
                }

                List<OrderVO> listOrder = orderDAO.findByTradeCode(orderVO);
                if (listOrder != null && listOrder.size() > 0) {
                    result.put("isOk", "n");
                    result.put("errormessage", "来源单号:"+order.getTradeCode()+"来源单号已经存在");
                    return result;
                }

                // 该订单的商品中存在实际单价为0的商品，您确认要保存该订单信息吗？
                if (vo.getFactUnitPrice() == null || vo.getFactUnitPrice().compareTo(BigDecimal.ZERO) == 0) {
                    isZeroFactUnitPrice = true;
                    break;
                }

                // 您要新增订单的商品金额(实际金额之和)不为0而支付金额为0，您确认要保存该订单信息吗？
                cash = cash.add(vo.getFactUnitPrice().multiply(new BigDecimal(vo.getQty())));

            }

            if (isZeroFactUnitPrice && "y".equals(orderInfo.getCheckPrice())) {
                result.put("isOk", "q_Price");
                result.put("errormessage", "来源单号:"+order.getTradeCode()+"该订单的商品中存在实际单价为0的商品，您确认要保存该订单信息吗？");
                return result;
            }

            // 您要新增订单的商品金额(实际金额之和)不为0而支付金额为0，您确认要保存该订单信息吗？
            if ("y".equals(orderInfo.getCheckCash()) && cash.compareTo(BigDecimal.ZERO) > 0
                    && (order.getPaidFee() == null || order.getPaidFee().compareTo(BigDecimal.ZERO) == 0)) {
                result.put("isOk", "q_cash");
                result.put("errormessage", "来源单号:"+order.getTradeCode()+"您要新增订单的商品金额(实际金额之和)不为0而支付金额为0，您确认要保存该订单信息吗？");
                return result;
            }

        } else if ("update".equals(orderInfo.getAction())) {

            if (orderInfo.getOrder() != null) {
                Order order = orderInfo.getOrder();
                if (!"sku".equals(orderInfo.getType())) {
                    // 订单来源不能为空
                    // if (StringUtils.isBlank(order.getShopType())) {
                    // result.put("isOk", "n");
                    // result.put("errormessage", "订单来源为空");
                    // return result;
                    // }

                    // 来源单号不能为空
                    if (StringUtils.isBlank(order.getTradeCode())) {
                        result.put("isOk", "n");
                        result.put("errormessage", "来源单号为空");
                        return result;
                    }

                    // 订单类型不能为空
                    if (StringUtils.isBlank(order.getOrderType())) {
                        result.put("isOk", "n");
                        result.put("errormessage", "订单类型为空");
                        return result;
                    }

                    // 支付方式不能为空
                    if (StringUtils.isBlank(order.getPayMode())) {
                        result.put("isOk", "n");
                        result.put("errormessage", "支付方式为空");
                        return result;
                    }

                    // 客户ID不能为空
                    if (StringUtils.isBlank(order.getBuyerNick())) {
                        result.put("isOk", "n");
                        result.put("errormessage", "客户ID为空");
                        return result;
                    }

                    // 网店不能为空
                    if (StringUtils.isBlank(order.getShopId())) {
                        result.put("isOk", "n");
                        result.put("errormessage", "网店为空");
                        return result;
                    }

                    // 发货仓库不能为空
                    if (StringUtils.isBlank(order.getStorId())) {
                        result.put("isOk", "n");
                        result.put("errormessage", "发货仓库为空");
                        return result;
                    }

//                    // 收货人不能为空
//                    if (StringUtils.isBlank(order.getCons())) {
//                        result.put("isOk", "n");
//                        result.put("errormessage", "收货人为空");
//                        return result;
//                    }

                    // 收货人不能为空
                    if (StringUtils.isBlank(order.getCons())) {
                        result.put("isOk", "n");
                        result.put("errormessage", "收货人为空");
                        return result;
                    }

                    // 收货人地址不能为空
                    if (StringUtils.isBlank(order.getConsAddr())) {
                        result.put("isOk", "n");
                        result.put("errormessage", "收货人地址为空");
                        return result;
                    }

                    // 固定电话与手机至少要输入一个 手机
                    if (StringUtils.isBlank(order.getConsTel()) && StringUtils.isBlank(order.getConsMobile())) {
                        result.put("isOk", "n");
                        result.put("errormessage", "固定电话与手机至少要输入一个 手机");
                        return result;
                    }

                    // if (!isMobile(order.getConsMobile())) {
                    // result.put("isOk", "n");
                    // result.put("errormessage", "手机输入不正确");
                    // return result;
                    // }

                    // if (!isFixedPhone(order.getConsTel())) {
                    // result.put("isOk", "n");
                    // result.put("errormessage", "固定电话输入不正确");
                    // return result;
                    // }
                }
                // 对sku列表进行check
                if (orderInfo.getArrSku() == null || orderInfo.getArrSku().size() <= 0) {
                    result.put("isOk", "n");
                    result.put("errormessage", "商品信息列表不能为空");
                    return result;
                }

                // 对sku列表进行check
                if (orderInfo.getArrSku() != null || orderInfo.getArrSku().size() > 0) {

                    List<OrderSkuVO> listOrderSku = orderInfo.getArrSku();
                    for (int i = 0; i < listOrderSku.size(); i++) {
                        OrderSkuVO vo = listOrderSku.get(i);
                        if (!"y".equals(vo.getDeleted())) {// 不是删除的时候
                            if (!"sku".equals(orderInfo.getType())) {
                                if (StringUtils.isBlank(vo.getGoodsCode())) {
                                    result.put("isOk", "n");
                                    result.put("errormessage", "商品商家编码不能为空");
                                    return result;
                                }

                                if (StringUtils.isBlank(vo.getGoodsName())) {
                                    result.put("isOk", "n");
                                    result.put("errormessage", "商品名称不能为空");
                                    return result;
                                }

                                if (StringUtils.isBlank(vo.getSkuCode())) {
                                    result.put("isOk", "n");
                                    result.put("errormessage", "规格商家编码不能为空");
                                    return result;
                                }

                                if (StringUtils.isBlank(vo.getSkuName())) {
                                    result.put("isOk", "n");
                                    result.put("errormessage", "规格名称不能为空");
                                    return result;
                                }

                                if (vo.getQty() == null || vo.getQty().intValue() <= 0) {
                                    result.put("isOk", "n");
                                    result.put("errormessage", "订购数量不能为空或者小于零");
                                    return result;
                                }
                            }
                        } else {
                            OrderSkuVO voP = new OrderSkuVO();
                            voP.setOrderSkuId(vo.getOrderSkuId());
                            OrderSkuVO orderSkuVO = orderSkuDAO.getOrderSkuList(voP).get(0);
                            if (!orderSkuVO.getDeleted().equals(vo.getDeleted())) { // 当画面数据由非删除状态到删除状态的时候，也就是删除动作
                                if (!"sku".equals(orderInfo.getType()) && (vo.getQty() == null || vo.getQty().intValue() <= 0)) {
                                    result.put("isOk", "n");
                                    result.put("errormessage", "订购数量不能为空或者小于零");
                                    return result;
                                }

                                // 待分派订单删除商品操作 校验：
                                OrderVO orderVO = orderDAO.findById(orderSkuVO.getOrderId());
                                if ("y".equals(vo.getDeleted()) && "i".equals(orderVO.getOrderStatus())) {

                                    // if (listOrderSku.size() == 1) {
                                    // // 订单下只存在一件商品，不能删除订单上商品！
                                    // result.put("isOk", "n");
                                    // result.put("errormessage",
                                    // "订单下只存在一件商品，不能删除订单上商品！");
                                    // return result;
                                    // }

                                    // 判断当前删除商品的发货中数和已发货数，如果任意一个数大于0，则提示！
                                    if ((orderSkuVO.getShippingQty() != null && orderSkuVO.getShippingQty() > 0)
                                            || (orderSkuVO.getShipedQty() != null && orderSkuVO.getShipedQty() > 0)) {
                                        result.put("isOk", "n");
                                        result.put("errormessage", "订单下的该商品存在未取消的出库单，不能删除订单上商品！");
                                        return result;
                                    }
                                }
                            }
                        }
                    }
                }

            }

        }

        result.put("isOk", "y");
        result.put("errormessage", "");
        return result;
    }
    /**
     * 添加Order
     *
     * @param entId
     * @return
     * @throws Exception
     */
    private String addOrder(Order order, String entId, String prjId, String prjShortName) throws Exception {
        OrderVO orderVO = new OrderVO();
        String orderId = java.util.UUID.randomUUID().toString().replaceAll("-", "");
        order.setPrjId(prjId);
        order.setEntId(entId);
        order.setOrderCode("OR" + prjShortName + CodeUtil.getCode());
        order.setOrderId(orderId);
        if (StringUtils.isBlank(order.getOperStus())) {
            order.setOperStus(OrderOperStatusConsts.MANUAL_AUTHEN);
        }
        order.setOrderTime(new Date());
        order.setShopType("其它");
        Stor stor = stroDAO.findByid(order.getStorId());
        order.setStorCode(stor.getStorCode());
        // if (StringUtils.isNotBlank(order.getStorId())){
        // StorVO storVO = new StorVO();
        // storVO.setStorId(order.getStorId());
        // List<StorVO> listStor = storService.getStorByCondition(storVO);
        // if (listStor!=null && listStor.size()>0){
        // order.setsot
        // }
        // }
        BeanUtils.copyProperties(order,orderVO);
        orderDAO.insert(orderVO);
        return orderId;
    }

    /**
     * 添加Order
     *
     * @param entId
     * @return
     * @throws Exception
     */
    private String addOrderImport(Order order, String entId, String prjId, String prjShortName) throws Exception {
        OrderVO orderVO = new OrderVO();
        String orderId = java.util.UUID.randomUUID().toString().replaceAll("-", "");
        order.setPrjId(prjId);
        order.setEntId(entId);
        order.setOrderCode("OR" + prjShortName + CodeUtil.getCode());
        order.setOrderId(orderId);
        if (StringUtils.isBlank(order.getOperStus())) {
            order.setOperStus(OrderOperStatusConsts.MANUAL_AUTHEN);
        }
        order.setOrderTime(new Date());
//        order.setShopType(order.getShopType());
//        Stor stor = stroDAO.findByid(order.getStorId());
//        order.setStorCode(stor.getStorCode());
        // if (StringUtils.isNotBlank(order.getStorId())){
        // StorVO storVO = new StorVO();
        // storVO.setStorId(order.getStorId());
        // List<StorVO> listStor = storService.getStorByCondition(storVO);
        // if (listStor!=null && listStor.size()>0){
        // order.setsot
        // }
        // }
        BeanUtils.copyProperties(order,orderVO);

        ShopVO vo = new ShopVO();
        vo.setShopAccount(order.getShopName());
        vo.setShopType(order.getShopType());
        List<ShopVO> listshop  = shopDAO.findByWhereByShopAccount(vo);
        orderVO.setShopAccount(listshop.get(0).getShopAccount());
        orderVO.setShopType(listshop.get(0).getShopType());
        orderVO.setShopId(listshop.get(0).getShopId());
        orderVO.setShopName(listshop.get(0).getShopName());

        ShopStorVO shopStorVO = new ShopStorVO();
        shopStorVO.setShopId(listshop.get(0).getShopId());
        shopStorVO.setStorCode(order.getStorCode());
        List<ShopStorVO> listShopStor = shopStorService.getShopStorListByShopStor(shopStorVO);
        orderVO.setStorCode(listShopStor.get(0).getStorCode());
        orderVO.setStorId(listShopStor.get(0).getStorId());
        orderVO.setStorName(listShopStor.get(0).getStorName());

        LogisticsVO lgstVO = new LogisticsVO();
        lgstVO.setPrjId(prjId);
        lgstVO.setLgstCode(order.getLgstCode());
        List<LogisticsVO> listLgst = lgstDAO.getLgstByCondition(lgstVO);
        orderVO.setLgstCode(listLgst.get(0).getLgstCode());
        orderVO.setLgstName(listLgst.get(0).getLgstName());
        orderVO.setLgstId(listLgst.get(0).getLgstId());

        Map<String,String> mapArea = new HashMap<String,String>();
        mapArea.put("province",order.getProvName());
        mapArea.put("city",order.getCityName());
        mapArea.put("district",order.getDistName());
        List<TopArea> list = topAreaDAO.getAreaCode(mapArea,"selectByAreaName");
        orderVO.setAreaCoding(Integer.valueOf(list.get(0).getAreaCode()));

        orderDAO.insert(orderVO);
        return orderId;
    }

    private void updateOrder(Order order, String entId, String prjId, String prjShortName) throws Exception {
        OrderVO orderVO = new OrderVO();
        order.setPrjId(prjId);
        order.setEntId(entId);
        order.setUpdateTime(new Date());
        order.setCreateTime(new Date());
        Stor stor = stroDAO.findByid(order.getStorId());
        order.setStorCode(stor.getStorCode());
        BeanUtils.copyProperties(order,orderVO);
        orderDAO.update(orderVO);
    }

    public void update(OrderVO orderVO) throws Exception {
        orderDAO.update(orderVO);
    }

    public int updateOrderForConsign(OrderVO orderVO) throws Exception {
        return orderDAO.updateOrderForConsign(orderVO);
    }

    private Map<String, Object> updateOrderSku(List<OrderSkuVO> list, String updateSkuQ) throws Exception {
        Map<String, Object> returnMap = new HashMap<String, Object>();
        List<OrderSkuVO> listReturn = new ArrayList<OrderSkuVO>();
        List<OrderVO> listDelOrder = new ArrayList<OrderVO>();
        StringBuilder qmsg = new StringBuilder();
        if (list != null && list.size() > 0) {
            List<String> querySysStatus = new ArrayList<String>();
            querySysStatus.add("a");
            querySysStatus.add("e");
            querySysStatus.add("d");
            querySysStatus.add("b");
            for (int i = 0; i < list.size(); i++) {
                OrderSkuVO vo = list.get(i);
                vo.setUpdateTime(new Date());
                if ("update".equals(vo.getAction())) {
                    OrderSkuVO voP = new OrderSkuVO();
                    voP.setOrderSkuId(vo.getOrderSkuId());
                    OrderSkuVO orderSkuVO = orderSkuDAO.getOrderSkuList(voP).get(0);

                    if ("y".equals(vo.getDeleted()) && !orderSkuVO.getDeleted().equals(vo.getDeleted())) {
                        boolean flg = false;
                        // 您选择的订单的该条商品不存在已完成的退款单，是否仍然删除该商品？
                        if ("y".equals(updateSkuQ)) {
                            SysRefundVO sysRefundVO = new SysRefundVO();
                            sysRefundVO.setOrderId(orderSkuVO.getOrderId());
                            sysRefundVO.setQuerySkuCode(orderSkuVO.getSkuCode());
                            sysRefundVO.setQuerySysStatus(querySysStatus);
                            sysRefundVO.setIsCancel("n");
                            List<SysRefundVO> listRefund = sysRefundService.getSysRefundListByCondition(sysRefundVO);
                            if (listRefund != null && listRefund.size() > 0) {
                                listReturn.add(vo);
                                qmsg.append(orderSkuVO.getGoodsCode() + "订单商品存在未完成的退款单，是否仍然删除该商品？\\n");
                                flg = true;
                            }
                        }

                        if (!flg) {
                            // 保存：
                            // 1、删除当前商品
                            orderSkuDAO.update(vo);

                            // 2、如果是合并订单，那么合并前的这个商品也要删除掉哦~~
                            OrderVO orderVO = orderDAO.findById(orderSkuVO.getOrderId());
                            listDelOrder.add(orderVO);
                            if ("c".equals(orderVO.getCombStus())) {
                                OrderSkuVO combOrderSku = new OrderSkuVO();
                                if (StringUtils.isNotBlank(orderSkuVO.getTradeCode())) {
                                    combOrderSku.setTradeCode(orderSkuVO.getTradeCode());
                                    combOrderSku.setSkuId(orderSkuVO.getSkuId());
                                    if (StringUtils.isNotBlank(orderSkuVO.getOid())) {
                                        combOrderSku.setOid(orderSkuVO.getOid());
                                    }
                                    combOrderSku.setDeleted("y");
                                    combOrderSku.setUpdateTime(new Date());
                                    orderSkuDAO.updateByCondition(combOrderSku);
                                }
                            }

                            // 对sku的数据进行判断，是否需要变更为发货中状态
                            if ("i".equals(orderVO.getOrderStatus())) {
                                OrderSkuVO voWhere = new OrderSkuVO();
                                voWhere.setOrderId(orderSkuVO.getOrderId());
                                voWhere.setDeleted("n");
                                List<OrderSkuVO> otherSkus = orderSkuDAO.getOrderSkuList(voWhere);
                                if (otherSkus != null) {
                                    int shipping = 0;
                                    int shipped = 0;
                                    for (int j = 0; j < otherSkus.size(); j++) {
                                        if (otherSkus.get(j).getShippingQty() != null && otherSkus.get(j).getShippingQty()
                                                .intValue() == otherSkus.get(j).getQty().intValue()) {
                                            shipping++;
                                        } else if (otherSkus.get(j).getShipedQty() != null
                                                && otherSkus.get(j).getShipedQty().intValue() == otherSkus.get(j).getQty().intValue()) {
                                            shipped++;
                                        } else {
                                            break;
                                        }
                                    }

                                    // 发货中
                                    if (shipping > 0 && otherSkus.size() == shipping + shipped) {
                                        orderVO.setOrderStatus("k");
                                        orderDAO.update(orderVO);
                                    }

                                    // 已经发货
                                    if (shipped > 0 && otherSkus.size() == shipped) {
                                        orderVO.setOrderStatus("r");
                                        orderDAO.update(orderVO);
                                    }
                                }
                            }
                        }
                    } else {
                        orderSkuDAO.update(vo);
                    }
                } else {
                    vo.setCreateTime(new Date());
                    vo.setOrderSkuId(java.util.UUID.randomUUID().toString().replaceAll("-", ""));
                    OrderVO orderVO = orderDAO.findById(vo.getOrderId());
                    vo.setTradeCode(orderVO.getTradeCode());

                    GoodsSku goodsSkuTemp = goodsService.getGoodsSkuBySkuId(vo.getSkuId());
                    vo.setGoodsSkuCost(goodsSkuTemp.getCostPrice());

                    orderSkuDAO.insert(vo);
                }
            }
            // 3、更新订单状态逻辑：
            // 判断被删除的商品以外的其他商品，
            for (int i = 0; i < listDelOrder.size(); i++) {
                OrderVO ordervo = listDelOrder.get(i);
                OrderSkuVO orderSkuVO = new OrderSkuVO();
                orderSkuVO.setOrderId(ordervo.getOrderId());
                orderSkuVO.setDeleted("n");
                List<OrderSkuVO> listOrderSku = orderSkuDAO.getOrderSkuList(orderSkuVO);
                boolean shippedFlg = true;
                if (listOrderSku != null && listOrderSku.size() > 0) {
                    for (int j = 0; j < listOrderSku.size(); j++) {
                        int qty = listOrderSku.get(j).getQty() != null ? listOrderSku.get(j).getQty().intValue() : 0;
                        int shipping_qty = listOrderSku.get(j).getShippingQty() != null
                                ? listOrderSku.get(j).getShippingQty().intValue() : 0;
                        int shiped_qty = listOrderSku.get(j).getShipedQty() != null ? listOrderSku.get(j).getShipedQty().intValue() : 0;
                        // 1)、如果存在（订购数 > 发货中数 + 已发货数）的商品，订单状态不变，结束当前操作。return
                        if (qty > (shipping_qty + shiped_qty)) {
                            shippedFlg = false;
                            break;
                        } else if (qty == (shipping_qty + shiped_qty)) {
                            // 2)、若果存在发货中数大于0的商品，订单打成发货中状态，同时清掉所有问题单标识。return
                            if (shipping_qty != 0) {
                                ordervo.setOrderErrorRemark("");
                                ordervo.setGoodsErrorRemark("");
                                ordervo.setLgstErrorRemark("");
                                ordervo.setStockErrorRemark("");

                                ordervo.setIsOrderError("n");
                                ordervo.setIsGoodsError("n");
                                ordervo.setIsLgstError("n");
                                ordervo.setIsStockError("n");

                                ordervo.setUpdateTime(new Date());
                                orderDAO.update(ordervo);
                                shippedFlg = false;
                                break;
                            } else if (shipping_qty == 0) {

                            } else {
                                shippedFlg = false;
                            }
                        }
                    }
                }
                // 3)、若果存在发货中数都等于0并且已发货数都等于订购数的商品，订单打成已发货状态。return
                if (shippedFlg) {
                    ordervo.setOrderStatus("r");
                    ordervo.setUpdateTime(new Date());
                    orderDAO.update(ordervo);
                }
            }
        }
        returnMap.put("qlist", listReturn);
        returnMap.put("qmsg", qmsg.toString());
        return returnMap;
    }

    private String addOrderSkuImport(OrderSkuVO orderSkuVO, String orderId, String entId, String prjId, Order order) throws Exception {
        orderSkuVO.setOrderSkuId(java.util.UUID.randomUUID().toString().replaceAll("-", ""));
        orderSkuVO.setOrderId(orderId);
        orderSkuVO.setTradeCode(order.getTradeCode());

//        GoodsSku goodsSkuTemp = goodsService.getGoodsSkuBySkuId(orderSkuVO.getSkuId());
//        orderSkuVO.setGoodsSkuCost(goodsSkuTemp.getCostPrice());
        GoodsSkuVO vo  = new GoodsSkuVO();
        vo.setPrjId(prjId);
        vo.setSkuCode(orderSkuVO.getSkuCode());
        List<GoodsSkuVO> goodsSkuVOList = findPage("selectGoodsSkuListBySkuCode", vo);
        orderSkuVO.setGoodsName(goodsSkuVOList.get(0).getGoodsName());
        orderSkuVO.setGoodsCode(goodsSkuVOList.get(0).getGoodsCode());
        orderSkuVO.setGoodsId(goodsSkuVOList.get(0).getGoodsId());
        orderSkuVO.setGoodsSkuCost(goodsSkuVOList.get(0).getCostPrice());
        orderSkuVO.setSkuCode(goodsSkuVOList.get(0).getSkuCode());
        orderSkuVO.setSkuName(goodsSkuVOList.get(0).getSkuName());
        orderSkuVO.setSkuId(goodsSkuVOList.get(0).getSkuId());
        orderSkuVO.setSalePrice(goodsSkuVOList.get(0).getSalePrice());
        orderSkuVO.setIsGift("n");
        orderSkuVO.setIsVirt(goodsSkuVOList.get(0).getVirtYn());
        if (orderSkuVO.getFactUnitPrice()!=null && orderSkuVO.getQty()!=null){
            orderSkuVO.setDivideOrderFee(orderSkuVO.getFactUnitPrice().multiply(BigDecimal.valueOf(orderSkuVO.getQty())));
        }
        orderSkuDAO.insert(orderSkuVO);
        return orderSkuVO.getOrderSkuId();
    }
    /**
     * 添加系统规格
     *
     * @return
     * @throws Exception
     */
    private String addOrderSku(OrderSkuVO orderSkuVO, String orderId, String entId, Order order) throws Exception {
        // orderSkuVO.setEcSkuId(orderSkuVO.getSkuId());
        // orderSkuVO.setEcSkuCode(orderSkuVO.getSkuCode());
        // orderSkuVO.setEcSkuName(orderSkuVO.getSkuName());
        // orderSkuVO.setEcItemId(orderSkuVO.getGoodsId());
        // orderSkuVO.setEcItemCode(orderSkuVO.getGoodsCode());
        // orderSkuVO.setEcItemName(orderSkuVO.getGoodsName());
        orderSkuVO.setOrderSkuId(java.util.UUID.randomUUID().toString().replaceAll("-", ""));
        orderSkuVO.setOrderId(orderId);
        orderSkuVO.setTradeCode(order.getTradeCode());

        GoodsSku goodsSkuTemp = goodsService.getGoodsSkuBySkuId(orderSkuVO.getSkuId());
        orderSkuVO.setGoodsSkuCost(goodsSkuTemp.getCostPrice());
//        if (orderSkuVO.getFactUnitPrice()!=null && orderSkuVO.getQty()!=null){
//            orderSkuVO.setDivideGoodsFee(orderSkuVO.getFactUnitPrice().multiply(BigDecimal.valueOf(orderSkuVO.getQty())));
//        }
        orderSkuDAO.insert(orderSkuVO);
        return orderSkuVO.getOrderSkuId();
    }

    /**
     * 系统订单数据跟新
     */
    @Override
    public Map<String, Object> modifyOrderData(OrderInfoList orderInfoList, Map<String, String> map) throws Exception{
        Map<String, Object> result = new HashMap<String, Object>();

        boolean flg = true;
        for (int i = 0 ;i < orderInfoList.getOrderInfoVOs().size(); i++){
            orderInfoList.getOrderInfoVOs().get(i).setCheckCash(orderInfoList.getCheckCash());
            orderInfoList.getOrderInfoVOs().get(i).setCheckPrice(orderInfoList.getCheckPrice());
            Map<String, String> checkMap = checkOrderInfoImport(orderInfoList.getOrderInfoVOs().get(i), map);
            if (!"y".equals(checkMap.get("isOk"))) {
                flg=false;
                result.put("isOk", checkMap.get("isOk"));
                result.put("count", "0");
                if (result.get("errormessage")==null){
                    result.put("errormessage",(String)checkMap.get("errormessage"));
                } else {
                    result.put("errormessage", result.get("errormessage")==null?"":(String)result.get("errormessage")+"。\\n"+(String)checkMap.get("errormessage"));
                }
            }
        }
        if (!flg){
            return result;
        }

        for (int i = 0 ;i < orderInfoList.getOrderInfoVOs().size(); i++){
            Order order = orderInfoList.getOrderInfoVOs().get(i).getOrder();
            List<OrderSkuVO> list = orderInfoList.getOrderInfoVOs().get(i).getArrSku();
            // 追加order数据
            String id = addOrderImport(order, map.get("entId"), map.get("prjId"), map.get("prjShortName"));
            for (int j = 0; j < list.size(); j++) {
                OrderSkuVO orderSkuVO = list.get(j);

                // 追加OrderSku数据
                String orderSkuId = addOrderSkuImport(orderSkuVO, id, map.get("entId"), map.get("prjId"), order);
                map.put("orderSkuId", orderSkuId);
                map.put("orderId", id);
            }
        }
        result.put("isOk", "y");
        result.put("count", orderInfoList.getOrderInfoVOs().size());
        result.put("errormessage", "");
        return result;
    }

    /**
     * 系统订单数据跟新
     */
    @Override
    public Map<String, Object> modifyOrderData(OrderInfoVO orderInfo, Map<String, String> map) throws Exception {
        Map<String, Object> result = new HashMap<String, Object>();

        Map<String, String> checkMap = checkOrderInfo(orderInfo, map);
        if (!"y".equals(checkMap.get("isOk"))) {
            result.put("isOk", checkMap.get("isOk"));
            result.put("count", "0");
            result.put("errormessage", checkMap.get("errormessage"));
            return result;
        }

        Order order = orderInfo.getOrder();
        List<OrderSkuVO> list = orderInfo.getArrSku();

        // 校验通过后，新增系统商品及系统规格
        if ("insert".equals(orderInfo.getAction())) {
            // 追加order数据
            String id = addOrder(order, map.get("entId"), map.get("prjId"), map.get("prjShortName"));
            for (int i = 0; i < list.size(); i++) {
                OrderSkuVO orderSkuVO = list.get(i);

                // 追加OrderSku数据
                // 如果订单是手动创建的，就将实际金额覆盖sku的实际支付金额
                if(StringUtils.isEmpty(order.getTradeStatus())) {
                    for(OrderSkuVO orderSku : list) {
                        orderSkuVO.setDivideOrderFee(new BigDecimal(orderSku.getActualAmount()));
                    }
                }
                String orderSkuId = addOrderSku(orderSkuVO, id, map.get("entId"), order);
                map.put("orderSkuId", orderSkuId);
                map.put("orderId", id);
            }

        } else if ("update".equals(orderInfo.getAction())) {
            if (StringUtils.isBlank(order.getOrderId())) {// 删除、恢复
                Map<String, Object> mapOrderSku = updateOrderSku(orderInfo.getArrSku(), map.get("updateSkuQ"));
                result.put("qlist", mapOrderSku.get("qlist"));
                result.put("qmsg", mapOrderSku.get("qmsg"));

            } else {
                updateOrder(order, map.get("entId"), map.get("prjId"), map.get("prjShortName"));

                // 如果订单是手动创建的，就将实际金额覆盖sku的实际支付金额
                if(StringUtils.isEmpty(order.getTradeStatus())) {
                    for(OrderSkuVO orderSku : orderInfo.getArrSku()) {
                        orderSku.setDivideOrderFee(new BigDecimal(orderSku.getActualAmount()));
                    }
                }
                Map<String, Object> mapOrderSku = updateOrderSku(orderInfo.getArrSku(), map.get("updateSkuQ"));
                result.put("qlist", mapOrderSku.get("qlist"));
                result.put("qmsg", mapOrderSku.get("qmsg"));
            }

        } else if ("delete".equals(orderInfo.getAction())) {

        }

        result.put("isOk", "y");
        result.put("count", "1");
        result.put("errormessage", "");
        return result;
    }

    @Override
    public List<OrderVO> findCounts(OrderVO orderVO) throws Exception {
        List<OrderVO> list = findPage("selectOrderCounts", orderVO);
        return list;
    }

    /**
     * 验视订单
     * <p>
     * 更新has_inspected(已验视)状态
     *
     * @param orderId 系统订单id
     */
    @Override
    public int inspectedOrder(String orderId, String value) throws Exception {
        if (StringUtils.isNotBlank(orderId)) {
            String[] temp = orderId.split(",");
            if (temp.length > 0) {
                int result = 0;
                boolean flg = true;
                for (int i = 0; i < temp.length; i++) {
                    OrderVO orderVO = new OrderVO();
                    if ("au".equals(orderDAO.findById(temp[i]).getOperStus())) {
                        flg = false;
                    } else {
                        orderVO.setHasInspected(value);
                        orderVO.setOrderId(temp[i]);
                        result = result + orderDAO.update(orderVO);
                    }
                }
                if (flg) {
                    return result;
                } else {
                    return -1;
                }

            } else {
                return 0;
            }
        } else {
            return 0;
        }
    }

    /**
     * OrderSku的取得
     */
    @Override
    public List<OrderSkuVO> getOrderSku(OrderSkuVO orderSkuVO) throws Exception {
        if (orderSkuVO == null) {
            return null;
        }
        // OrderSkuVO vo = new OrderSkuVO();
        // vo.setOrderId(orderId);
        return orderSkuDAO.getOrderSkuList(orderSkuVO);
    }

    /**
     * OrderSku的取得
     */
    @Override
    public List<OrderSkuVO> getOrderSku(String orderId) throws Exception {
        if (StringUtils.isBlank(orderId)) {
            return null;
        }
        OrderSkuVO vo = new OrderSkuVO();
        vo.setOrderId(orderId);
        vo.setDeleted("n");
        return orderSkuDAO.getOrderSkuList(vo);
    }

    @Override
    public int getOngoingOrdersBySkuCode(Map paramMap) throws Exception {
        return orderDAO.getOngoingOrdersCountBySkuCode(paramMap);
    }

    /**
     * 全部OrderSku的取得，包括未删除和已删除的
     */
    @Override
    public List<OrderSkuVO> getAllOrderSku(String orderId) throws Exception {
        if (StringUtils.isBlank(orderId)) {
            return null;
        }
        OrderSkuVO vo = new OrderSkuVO();
        vo.setOrderId(orderId);
        return orderSkuDAO.getOrderSkuList(vo);
    }

    /**
     * @throws Exception
     * @see cn.rkylin.oms.order.service.IOrderService#getOrderSkuByRefundId(java.lang.String)
     */
    @Override
    public List<OrderSkuVO> getOrderSkuByRefundId(String refundId) throws Exception {
        if (StringUtils.isBlank(refundId)) {
            return null;
        }
        return orderSkuDAO.getOrderSkuList(refundId);
    }

    @Override
    public List<OrderSkuVO> getOrderSkuList(OrderSkuVO orderSkuVO) throws Exception {
        return orderSkuDAO.getOrderSkuList(orderSkuVO);
    }

    @Override
    public int updateOrderSku(OrderSkuVO vo) throws Exception {
        return orderSkuDAO.updateByCondition(vo);
    }

    @Override
    public int GetUnallotQty(String entId, String skuId, String storId) throws Exception {
        return 0;
    }

    /**
     * 手动订单下载
     */
    @Override
    public Map<String, String> downLoadOrder(DownLoadVO downLoadVO) throws Exception {
        Map<String, String> returnMap = new HashMap<String, String>();

        // 必须入力检查
        if (downLoadVO == null) {
            returnMap.put("success", "n");
            returnMap.put("errormessage", "传递的参数是空");
            return returnMap;
        }

        // 店铺
        if (StringUtils.isBlank(downLoadVO.getShopId())) {
            returnMap.put("success", "n");
            returnMap.put("errormessage", "网店是空");
            return returnMap;
        }

        if ("b".equals(downLoadVO.getChoise())) {
            // 买家昵称
            if (StringUtils.isBlank(downLoadVO.getBuyerNick())) {
                returnMap.put("success", "n");
                returnMap.put("errormessage", "顾客昵称是空");
                return returnMap;
            }
            downLoadVO.setEcTradeCode("");
        } else if ("t".equals(downLoadVO.getChoise())) {
            // 平台单号
            if (StringUtils.isBlank(downLoadVO.getEcTradeCode())) {
                returnMap.put("success", "n");
                returnMap.put("errormessage", "平台单号是空");
                return returnMap;
            }
            downLoadVO.setBuyerNick("");
        }

        // 下载平台订单
        String url = "";
        if ("淘宝".equals(downLoadVO.getShopType())) {
            if (StringUtils.isBlank(ectradeUrl)) {
                returnMap.put("success", "n");
                returnMap.put("errormessage", "平台订单下载地址不存在");
                return returnMap;
            }
            url = ectradeUrl + "?shopId=" + downLoadVO.getShopId();
            if (StringUtils.isNotBlank(downLoadVO.getEcTradeCode())) {
                // url = url + "&ecTradeCode=" +
                // URLEncoder.encode(downLoadVO.getEcTradeCode(), "utf-8");;
                url = url + "&ecTradeCode=" + downLoadVO.getEcTradeCode();
                ;
            }
            if (StringUtils.isNotBlank(downLoadVO.getBuyerNick())) {
                url = url + "&buyerNick=" + URLEncoder.encode(downLoadVO.getBuyerNick(), "utf-8");
            }
        } else if ("小V铺".equals(downLoadVO.getShopType())) {
            if (StringUtils.isBlank(gateway)) {
                returnMap.put("success", "n");
                returnMap.put("errormessage", "小V铺平台订单下载地址不存在");
                return returnMap;
            }
            if (StringUtils.isNotBlank(downLoadVO.getEcTradeCode())) {
                url = gateway + "/xvp-microservice/order/getXvpOrderIdQuery?shopId=" + downLoadVO.getShopId() + "&orderId=" + downLoadVO.getEcTradeCode();
            }
            if (StringUtils.isNotBlank(downLoadVO.getBuyerNick())) {
                url = gateway + "/xvp-microservice/order/getXvpOrderUserIdQuery?shopId=" + downLoadVO.getShopId() + "&userId=" + downLoadVO.getBuyerNick();
            }
        } else if ("唯品会直发".equals(downLoadVO.getShopType())) {
            if (StringUtils.isBlank(gateway)) {
                returnMap.put("success", "n");
                returnMap.put("errormessage", "唯品会直发平台订单下载地址不存在");
                return returnMap;
            }
            if (StringUtils.isNotBlank(downLoadVO.getEcTradeCode())) {
                url = gateway + "/microservice-vip/trade/downloadVipOrderByEcTradeCode?shopId=" + downLoadVO.getShopId() + "&ecTradeCode=" + downLoadVO.getEcTradeCode();
            }
        }
        else if ("网易考拉".equals(downLoadVO.getShopType())) {
            if (StringUtils.isBlank(gateway)) {
                returnMap.put("success", "n");
                returnMap.put("errormessage", "网易考拉平台订单下载地址不存在");
                return returnMap;
            }
            if (StringUtils.isNotBlank(downLoadVO.getEcTradeCode())) {
                url = gateway + "/microservice-kaola/order/downloadKaolaOrderByEcTradeCode?shopId=" + downLoadVO.getShopId() + "&ecTradeCode=" + downLoadVO.getEcTradeCode();
            }
        }
        else if ("京东".equals(downLoadVO.getShopType())) {
            if (StringUtils.isBlank(gateway)) {
                returnMap.put("success", "n");
                returnMap.put("errormessage", "京东平台订单下载地址不存在");
                return returnMap;
            }
            if (StringUtils.isNotBlank(downLoadVO.getEcTradeCode())) {
                url = gateway + "/microservice-jd/order/downloadJdOrderByEcTradeCode?shopId=" + downLoadVO.getShopId() + "&ecTradeCode=" + downLoadVO.getEcTradeCode();
            }
        }
        else if ("苏宁".equals(downLoadVO.getShopType())) {
            if (StringUtils.isBlank(gateway)) {
                returnMap.put("success", "n");
                returnMap.put("errormessage", "苏宁平台订单下载地址不存在");
                return returnMap;
            }
            if (StringUtils.isNotBlank(downLoadVO.getEcTradeCode())) {
                url = gateway + "/microservice-suning/order/downloadSuningOrderByEcTradeCode?shopId=" + downLoadVO.getShopId() + "&ecTradeCode=" + downLoadVO.getEcTradeCode();
            }
        }
        else if ("商城".equals(downLoadVO.getShopType())) {
            if (StringUtils.isBlank(gateway)) {
                returnMap.put("success", "n");
                returnMap.put("errormessage", "商城平台订单下载地址不存在");
                return returnMap;
            }
            if (StringUtils.isNotBlank(downLoadVO.getEcTradeCode())) {
                url = gateway + "/microservice-yiyouyayin/order/downloadYiOrderByEcTradeCode?shopId=" + downLoadVO.getShopId() + "&ecTradeCode=" + downLoadVO.getEcTradeCode();
            }
        }


        Map<String, String> postData = new HashMap<String, String>();
        List<String> repeatNames = new ArrayList<String>();
        List<String> repeatValues = new ArrayList<String>();
        // 通过httpClient实现跨域调用的OMSJobExecutor重新分单的操作
        // String result = HttpUtils.postMethod(url, postData, repeatNames,
        // repeatValues);
        String result = HttpUtils.sendByGet(url, null);
        System.out.println(result);
        Map maps = (Map) JSON.parse(result);
        if (!maps.get("success").equals("true")) {
            returnMap.put("success", "n");
            returnMap.put("errormessage", "平台订单下载失败");
            return returnMap;
        }

        // 系统订单
        if (StringUtils.isBlank(sysOrderUrl)) {
            returnMap.put("success", "n");
            returnMap.put("errormessage", "系统订单下载地址不存在");
            return returnMap;
        }
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        String start = formatter.format(new Date()).toString();
        url = sysOrderUrl + "?shopId=" + downLoadVO.getShopId() + "&start=" + start + "&end=2999-12-01";
        if (StringUtils.isNotBlank(downLoadVO.getBuyerNick())) {
            url = url + "&buyerNick=" + URLEncoder.encode(downLoadVO.getBuyerNick(), "utf-8");
        }
        if (StringUtils.isNotBlank(downLoadVO.getEcTradeCode())) {
            url = url + "&tradeCode=" + downLoadVO.getEcTradeCode();
        }
        postData = new HashMap<String, String>();
        repeatNames = new ArrayList<String>();
        repeatValues = new ArrayList<String>();
        // 通过httpClient实现跨域调用的OMSJobExecutor重新分单的操作
        // result = HttpUtils.postMethod(url, postData, repeatNames,
        // repeatValues);
        result = HttpUtils.sendByGet(url, null);
        System.out.println(result);
        maps = (Map) JSON.parse(result);
        if (!maps.get("success").equals("true")) {
            returnMap.put("success", "n");
            returnMap.put("errormessage", "系统订单下载失败");
            return returnMap;
        }

        returnMap.put("success", "y");
        returnMap.put("errormessage", "");
        return returnMap;
    }

    /**
     * 退货单加载 订单商品以及订单关联补发单的商品
     *
     * @param orderId
     * @return
     * @throws Exception
     */
    @Override
    public List<OrderSkuVO> getOrderSkuAndResendSkuByOrderId(String orderId) throws Exception {
        if (StringUtils.isBlank(orderId)) {
            return null;
        }

        List<OrderSkuVO> returnValue = orderSkuDAO.getOrderSkuAndResendSkuByOrderId(orderId);

        for (OrderSkuVO orderSkuVO : returnValue) {
            if("or".equals(orderSkuVO.getDanjuType())) {
                orderSkuVO.setSn(snCodeExtractor.getSnCodeBySourceSkuId(orderSkuVO.getOrderSkuId(),"or",orderId));
            }else if("rs".equalsIgnoreCase(orderSkuVO.getDanjuType())) {
                if("rs".equalsIgnoreCase(orderSkuVO.getShangpinType())){
                    orderSkuVO.setSn(snCodeExtractor.getSnCodeBySourceSkuId(orderSkuVO.getOrderSkuId(),"rs",orderSkuVO.getOrderId()));
                }else {
                    orderSkuVO.setSn(snCodeExtractor.getSnCodeBySourceSkuId(orderSkuVO.getSourceSkuId(),"rs",orderSkuVO.getOrderId()));
                }
            }
        }

        return returnValue;
    }

    /**
     * 获取系统订单售后信息 wangxing add
     *
     * @param orderId
     * @return
     * @throws Exception
     */
    @Override
    public List<OrderVO> getOrderAftersaleInfo(String orderId) throws Exception {
        if (StringUtils.isBlank(orderId)) {
            return null;
        }
        return orderDAO.getOrderAftersaleInfo(orderId);
    }

    /**
     * 发货单取消的时候，订单相应的数据要进行修改
     */
    @Override
    public Map<String, Object> cancelShiporder(ShiporderVO shiporderVO) throws Exception {
        Map<String, Object> map = new HashMap<String, Object>();
        ShiporderSkuVO shiporderSkuVO = new ShiporderSkuVO();
        shiporderSkuVO.setShiporderId(shiporderVO.getShiporderId());
        List<ShiporderSkuVO> list = shiporderService.selectShiporderSkuList(shiporderSkuVO);
        if (list != null && list.size() > 0) {
            // 循环发货单的sku，修改订单的sku的发货中的数量
            for (int i = 0; i < list.size(); i++) {
                ShiporderSkuVO vo = list.get(i);
                OrderSkuVO orderSkuParm = new OrderSkuVO();
                orderSkuParm.setOrderSkuId(vo.getOrderSkuId());
                OrderSkuVO orderSkuVO = orderSkuDAO.getOrderSkuList(orderSkuParm).get(0);
                if (orderSkuVO != null) {
                    int shippingQty = orderSkuVO.getShippingQty() != null ? orderSkuVO.getShippingQty().intValue() : 0;
                    int backQty = vo.getQty() != null ? Integer.valueOf(vo.getQty()) : 0;
                    shippingQty = shippingQty - backQty;
                    orderSkuVO.setShippingQty(shippingQty);
                    orderSkuVO.setUpdateTime(new Date());
                    orderSkuDAO.update(orderSkuVO);
                }
            }

            // OrderVO orderVO = orderDAO.findById(shiporderVO.getSourceId());
            OrderVO orderVO = new OrderVO();
            orderVO.setOrderStatus("i");
            orderVO.setUpdateTime(new Date());
            orderVO.setOperStus("ma");
            orderVO.setOrderId(shiporderVO.getSourceId());
            orderDAO.update(orderVO);
        }
        map.put("result", "success");
        return map;
    }

    /**
     * 校验待审核状态下的订单平台规格
     *
     * @param orderSkuVO
     * @return
     * @throws Exception
     */
    @Override
    public List<OrderSkuVO> getOrderSkuWaitVerifyList(OrderSkuVO orderSkuVO) throws Exception {
        return orderSkuDAO.getOrderSkuWaitVerifyList(orderSkuVO);
    }

    /**
     * 平台商品关联系统商品同时更新待审核订单商品的系统商品
     *
     * @param vo
     * @return
     * @throws Exception
     */
    @Override
    public int updateOrderSkuForEcSku(OrderSkuVO vo) throws Exception {
        return orderSkuDAO.updateOrderSkuForEcSku(vo);
    }

    @Override
    public PageInfo<OrderVOForEvent> findByWhere(int page, int length, OrderVOForEvent param) throws Exception {
        PageInfo<OrderVOForEvent> orderVOList = findPage(page, length, "pageSelectOrderForEvent", param);
        return orderVOList;
    }

    @Override
    public int selectCount(Map<String, Object> params) throws Exception {
        return orderDAO.selectCount(params);
    }

    @Override
    public List<OrderExportVO> exportSku(Map map) throws Exception {
        if (map == null) {
            return null;
        }
        // OrderSkuVO vo = new OrderSkuVO();
        // vo.setOrderId(orderId);
        return orderDAO.exportSku(map);
    }

    /**
     * 获取系统订单商品明细
     *
     * @param orderSkuId
     * @return
     * @throws Exception
     */
    @Override
    public OrderSkuVO selectByPrimaryKeyOrderSku(String orderSkuId) throws Exception {
        if (StringUtils.isBlank(orderSkuId)) {
            return null;
        }
        return orderSkuDAO.selectByPrimaryKeyOrderSku(orderSkuId);
    }


    /**
     * 批量修改平台备注
     *
     * @param orderId
     * @param salesRemark
     * @param tbFlagCode
     * @return
     * @throws Exception
     */
    public String batchUpdateOrderSalesRemark(String orderId, String salesRemark, Long tbFlagCode) throws Exception {
        StringBuffer stringBuffer = new StringBuffer();
        if (StringUtils.isNotBlank(orderId)) {
            String[] temp = orderId.split(",");
            if (temp.length > 0) {
                for (int i = 0; i < temp.length; i++) {
                    String result = updateOrderSalesRemark(temp[i], salesRemark, tbFlagCode);
                    stringBuffer.append(result + "<br/>");
                }
            }
        }
        return stringBuffer.toString();
    }

    /**
     * 逐个修改平台备注
     *
     * @param orderId
     * @param salesRemark
     * @param tbFlagCode
     * @return
     * @throws Exception
     */
    private String updateOrderSalesRemark(String orderId, String salesRemark, Long tbFlagCode) throws Exception {
        String strRes = "";
        OrderVO orderFindVO = orderDAO.findById(orderId);
        if ("au".equalsIgnoreCase(orderFindVO.getOperStus())) {
            return orderFindVO.getOrderCode() + ":自动状态订单不能修改平台备注";
        } else {

            //调用API入参
            PushTradeMemo pushTradeMemo = new PushTradeMemo();
            pushTradeMemo.setShopId(orderFindVO.getShopId());
            pushTradeMemo.setTid(Long.valueOf(orderFindVO.getTradeCode()));
            pushTradeMemo.setFlag(tbFlagCode);
            pushTradeMemo.setMemo(salesRemark);

            String requestParams = JSON.toJSONString(pushTradeMemo);
            //开始调用修改平台备注API
            String resJson = HttpUtils.sendByPost(omsAddres + "pushTrade/pushTradeMemo.action", requestParams);
            //序列化返回信息
            Map<String, Object> resultMap = JSON.parseObject(resJson, Map.class);

            if (YesNoConst.YES.equals(resultMap.get("success"))) {
                //更新系统订单平台旗帜和卖家备注
                OrderVO orderVO = new OrderVO();
                orderVO.setOrderId(orderId);
                orderVO.setSalesRemark(salesRemark);
                orderVO.setTbFlagCode(tbFlagCode);
                orderVO.setUpdateTime(new Date());
                int iRes = orderDAO.update(orderVO);
                if (iRes > 0) {
                    logUtil.info(new DBLog(orderFindVO.getOrderCode(), "手动批量设置平台备注", "", "手动批量设置平台备注成功，平台旗帜："
                            + getFlagName(tbFlagCode) + "，卖家备注：" + salesRemark));
                }
                strRes = orderFindVO.getOrderCode() + ":修改完成";
            } else {
                strRes = orderFindVO.getOrderCode() + ":" + resultMap.get("msg");
            }
            return strRes;
        }
    }

    /**
     * 平台旗帜名称
     *
     * @param tbFlagCode
     * @return
     */
    private String getFlagName(Long tbFlagCode) {
        String strFlagName = "";
        if (tbFlagCode == 0) {
            strFlagName = "灰色";
        } else if (tbFlagCode == 1) {
            strFlagName = "红色";
        } else if (tbFlagCode == 2) {
            strFlagName = "黄色";
        } else if (tbFlagCode == 3) {
            strFlagName = "绿色";
        } else if (tbFlagCode == 4) {
            strFlagName = "蓝色";
        } else if (tbFlagCode == 5) {
            strFlagName = "粉色";
        }
        return strFlagName;
    }
    
	private boolean checkValue(String regex, String value) {
		Pattern pattern = Pattern.compile(regex);
		Matcher match = pattern.matcher(value);
		return (match.matches());
	}

	private String getAreaCode(String parentCode, String areaName) throws Exception {
		String areaCode = "";

		TopArea topArea = new TopArea();
		topArea.setParentCode(parentCode);
		List<TopArea> areaList = topAreaService.findAreaList(topArea);
		for (int j = 0; j < areaList.size(); j++) {
			TopArea area = areaList.get(j);
			if (area.getAreaName().equals(areaName)) {
				areaCode = area.getAreaCode();
				break;
			}
		}

		return areaCode;
	}

	@SuppressWarnings({ "unchecked", "deprecation" })
	public Map<String, Object> importCheck(Map<String, String> mapParm) throws Exception {

		String regexNum = "^[1-9][0-9]{0,10}$";
		String regexDouble = "^(([1-9][0-9]{0,10})|(([0]\\.\\d{1,2}|[1-9][0-9]{0,10}\\.\\d{1,2})))|[0]$";
		String regexPostCode = "^[0-9]{6}$";
		String regexLgstNo= "^[0-9]{1,50}$";
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
//		DecimalFormat df = new DecimalFormat("0.00"); 

		String json = mapParm.get("json");
		String mapAdjustSku = mapParm.get("mapAdjustSku");
		String prjId = mapParm.get("prjId");

		Map<String, Object> returnMap = new HashMap<String, Object>();
		if (StringUtils.isBlank(json)) {
			returnMap.put("result", "failed");
			returnMap.put("msg", "没有要导入的数据");
			return returnMap;
		}

		Map<String, String> mapTable = StringUtils.isBlank(mapAdjustSku) ? new HashMap<String, String>()
				: JSONObject.parseObject(mapAdjustSku, new TypeReference<Map<String, String>>() {
				});
		List<String> list = JSONArray.parseArray(json, String.class);
		List<OrderVO> listAdjustSkuVO = new ArrayList<OrderVO>(); // 页面显示用
		List<Map<String, String>> listError = new ArrayList<Map<String, String>>();
		if (list == null || list.size() <= 0) {
			returnMap.put("result", "failed");
			returnMap.put("msg", "没有要导入的数据");
			return returnMap;
		}

		boolean errorFlg = false;
		for (int i = 0; i < list.size(); i++) {
			Map<String, String> mapError = new HashMap<String, String>();
			String errorMsg = "";

			Map<String, String> map = JSONObject.parseObject(list.get(i), new TypeReference<Map<String, String>>() {
			});
			String shopAccount = map.get("网店账号");
			String shopType = map.get("平台");
			String tradeCode = map.get("来源单号");
			String buyerNick = map.get("客户ID");
			String storCode = map.get("发货仓库编码");
			String lgstCode = map.get("物流公司编码");
			String lgstNo = map.get("快递单号");
			String salesman = map.get("业务员");
			String remark = map.get("内部备注");
			String cons = map.get("姓名");
			String consMobile = map.get("手机");
			String consTel = map.get("固定电话");
			String consAddr = map.get("收货地址");
			String provName = map.get("省");
			String cityName = map.get("市");
			String distName = map.get("区");
			String consPostCode = map.get("邮编");
			String paidFee = map.get("支付金额");
			String paidDate = map.get("付款时间");
			String lgstFee = map.get("物流费用");
			String skuCode = map.get("规格商家编码");
			String qty = map.get("商品数量");
			String factUnitPrice = map.get("实际单价");
			String skuRemark = map.get("备注");

			if (mapTable.get(shopAccount + "-" + shopType + "-" + tradeCode + "-" + skuCode) != null) {
				errorMsg = errorMsg + " 数据重复";
			} else {
				mapTable.put(shopAccount + "-" + shopType + "-" + tradeCode + "-" + skuCode, "tempForCheck");
			}

			if (StringUtils.isBlank(shopAccount)) {
				errorMsg = errorMsg + " 网店账号:不能为空";
			}
			if (StringUtils.isBlank(shopType)) {
				errorMsg = errorMsg + " 平台:不能为空";
			}
			if (StringUtils.isBlank(tradeCode)) {
				errorMsg = errorMsg + " 来源单号:不能为空";
			}
			if (StringUtils.isBlank(buyerNick)) {
				errorMsg = errorMsg + " 客户ID:不能为空";
			}
			if (StringUtils.isBlank(cons)) {
				errorMsg = errorMsg + " 姓名:不能为空";
			}
			if (StringUtils.isBlank(consMobile) && StringUtils.isBlank(consTel)) {
				errorMsg = errorMsg + " 手机,固定电话必须填一个";
			}
			if (StringUtils.isBlank(consAddr)) {
				errorMsg = errorMsg + " 收货地址:不能为空";
			}
			if (StringUtils.isBlank(provName)) {
				errorMsg = errorMsg + " 省:不能为空";
			}
			if (StringUtils.isBlank(cityName)) {
				errorMsg = errorMsg + " 市:不能为空";
			}
			if (StringUtils.isBlank(paidFee)) {
				errorMsg = errorMsg + " 支付金额:不能为空";
			}
			if (StringUtils.isBlank(skuCode)) {
				errorMsg = errorMsg + " 规格商家编码:不能为空";
			}
			if (StringUtils.isBlank(qty)) {
				errorMsg = errorMsg + " 商品数量:不能为空";
			}
			if (StringUtils.isBlank(factUnitPrice)) {
				errorMsg = errorMsg + " 实际单价:不能为空";
			}

			if (!StringUtils.isBlank(lgstNo) && !checkValue(regexLgstNo, lgstNo)) {
				errorMsg = errorMsg + " 快递单号输入不正确";
			}
			if (!isMobile(consMobile)) {
				errorMsg = errorMsg + " 手机输入不正确";
			}
			if (!isFixedPhone(consTel)) {
				errorMsg = errorMsg + " 固定电话输入不正确";
			}
			if (!StringUtils.isBlank(consPostCode) && !checkValue(regexPostCode, consPostCode)) {
				errorMsg = errorMsg + " 邮编输入不正确";
			}
			if (!StringUtils.isBlank(paidFee) && !checkValue(regexDouble, paidFee)) {
				errorMsg = errorMsg + " 支付金额:请输入两位小数的合法数字";
			}
			if (!StringUtils.isBlank(paidDate)) {
				try {
					sdf.format(new Date(paidDate));
				} catch (Exception e) {
					errorMsg = errorMsg + " 付款时间:日期格式请按照yyyy-MM-dd HH:mm格式输入";
				}
			}
			if (!StringUtils.isBlank(lgstFee) && !checkValue(regexDouble, lgstFee)) {
				errorMsg = errorMsg + " 物流费用:请输入两位小数的合法数字";
			}
			if (!StringUtils.isBlank(factUnitPrice) && !checkValue(regexDouble, factUnitPrice)) {
				errorMsg = errorMsg + " 实际单价:请输入两位小数的合法数字";
			}
			if (!StringUtils.isBlank(qty) && !checkValue(regexNum, qty)) {
				errorMsg = errorMsg + " 商品数量:请输入非零整数字";
			}
			String shopId = "";
			if (!StringUtils.isBlank(shopType) && !StringUtils.isBlank(shopAccount)) {
				ShopVO shopVO = new ShopVO();
				shopVO.setPrjId(prjId);
				shopVO.setShopType(shopType);
				shopVO.setShopAccount(shopAccount);
				List<ShopVO> listshop = shopService.findByWhereByShopAccount(shopVO);
				if (listshop.size() == 0) {
					errorMsg = errorMsg + " 不存在对应的平台店铺";
				} else {
					ShopVO shopData = listshop.get(0);
					shopId = shopData.getShopId();
				}
			}
			if (!StringUtils.isBlank(shopId) && !StringUtils.isBlank(storCode)) {
				ShopStorVO shopStorVO = new ShopStorVO();
				shopStorVO.setShopId(shopId);
				shopStorVO.setStorCode(storCode);
				ShopStor shopStor = shopStorDAO.selectShopStorInfoByShopStor(shopStorVO);
				if (shopStor == null) {
					errorMsg = errorMsg + " 店铺下没有对应发货仓库";
				}
			}
			if (StringUtils.isBlank(storCode)) {
				ShopStorVO shopStorVO = new ShopStorVO();
				shopStorVO.setShopId(shopId);
				shopStorVO.setIsDefault(YesNoConst.YES);
				List<ShopStorVO> shopStorVOList = findPage("selectShopStorByCondition", shopStorVO);
				if (shopStorVOList.size() == 0) {
					errorMsg = errorMsg + " 该店铺没设置默认仓库";
				} else {
				    storCode = shopStorVOList.get(0).getStorCode();
				}
			}
			if (!StringUtils.isBlank(lgstCode)) {
				LogisticsVO lgstVO = new LogisticsVO();
				lgstVO.setPrjId(prjId);
				lgstVO.setLgstCode(lgstCode);
				List<LogisticsVO> lgstList = lgstDAO.getLgstByCondition(lgstVO);
				if (lgstList.size() == 0) {
					errorMsg = errorMsg + " 物流公司不存在";
				}
			}
			String areaCode = "";
			if (!StringUtils.isBlank(provName)) {
				areaCode = getAreaCode("1", provName);
				if (StringUtils.isBlank(areaCode)) {
					errorMsg = errorMsg + " 请输入正确的省";
				}
			}
			if (!StringUtils.isBlank(cityName) && !StringUtils.isBlank(areaCode)) {
				areaCode = getAreaCode(areaCode, cityName);
				if (StringUtils.isBlank(areaCode)) {
					errorMsg = errorMsg + " 请输入正确的市";
				}
			}
			if (!StringUtils.isBlank(distName) && !StringUtils.isBlank(areaCode)) {
				areaCode = getAreaCode(areaCode, distName);
				if (StringUtils.isBlank(areaCode)) {
					errorMsg = errorMsg + " 请输入正确的区";
				}
			}
			if (!StringUtils.isBlank(skuCode)) {
				GoodsSkuVO goodsSkuVO = new GoodsSkuVO();
				goodsSkuVO.setPrjId(prjId);
				goodsSkuVO.setSkuCode(skuCode);
				List<GoodsSkuVO> goodsSkuVOList = findPage("selectGoodsSkuListBySkuCode", goodsSkuVO);
				if (goodsSkuVOList.size() == 0) {
					errorMsg = errorMsg + " 规格商家编码不存在";
				}
			}

			if (StringUtils.isBlank(errorMsg)) {
				OrderVO orderVO = new OrderVO();
				orderVO.setShopAccount(shopAccount);
				orderVO.setShopType(shopType);
				orderVO.setTradeCode(tradeCode);
				orderVO.setBuyerNick(buyerNick);
				orderVO.setStorCode(storCode);
				orderVO.setLgstCode(lgstCode);
				orderVO.setLgstNo(lgstNo);
				orderVO.setSalesman(salesman);
				orderVO.setRemark(remark);
				orderVO.setCons(cons);
				orderVO.setConsMobile(consMobile);
				orderVO.setConsTel(consTel);
				orderVO.setConsAddr(consAddr);
				orderVO.setProvName(provName);
				orderVO.setCityName(cityName);
				orderVO.setDistName(distName);
				orderVO.setConsPostCode(consPostCode);
//				paidFee = df.format(Double.parseDouble(paidFee));
				if (!StringUtils.isBlank(paidFee)) {
				    orderVO.setPaidFee(new BigDecimal(paidFee));
				}
				if (!StringUtils.isBlank(paidDate)) {
				    orderVO.setPaidDate(new Date(paidDate));
				}
				if (!StringUtils.isBlank(lgstFee)) {
				    orderVO.setLgstFee(new BigDecimal(lgstFee));
				}
				orderVO.setSkuCode(skuCode);
				orderVO.setQty(qty);
				orderVO.setFactUnitPrice(factUnitPrice);
				orderVO.setSkuRemark(skuRemark);
				listAdjustSkuVO.add(orderVO);
			}
			
			mapError.put("错误信息", errorMsg);
			mapError.put("网店账号", shopAccount);
			mapError.put("平台", shopType);
			mapError.put("来源单号", tradeCode);
			mapError.put("客户ID", buyerNick);
			mapError.put("发货仓库编码", storCode);
			mapError.put("物流公司编码", lgstCode);
			mapError.put("快递单号", lgstNo);
			mapError.put("业务员", salesman);
			mapError.put("内部备注", remark);
			mapError.put("姓名", cons);
			mapError.put("手机", consMobile);
			mapError.put("固定电话", consTel);
			mapError.put("收货地址", consAddr);
			mapError.put("省", provName);
			mapError.put("市", cityName);
			mapError.put("区", distName);
			mapError.put("邮编", consPostCode);
			mapError.put("支付金额", paidFee);
			if (!StringUtils.isBlank(paidDate)) {
				mapError.put("付款时间", sdf.format(new Date(paidDate)));
			} else {
				mapError.put("付款时间", paidDate);
			}
			mapError.put("物流费用", lgstFee);
			mapError.put("规格商家编码", skuCode);
			mapError.put("商品数量", qty);
			mapError.put("实际单价", factUnitPrice);
			mapError.put("备注", skuRemark);
			listError.add(mapError);
			
			if (StringUtils.isNotBlank(errorMsg)) {
				errorFlg = true;
		    }
		}

		Comparator<OrderVO> comparator = new Comparator<OrderVO>() {
			public int compare(OrderVO s1, OrderVO s2) {
				if (!s1.getShopType().equals(s2.getShopType())) {
					// 先按平台排序
					return s1.getShopType().compareTo(s2.getShopType());
				} else {
					// 平台相同则按来源单号排序
					return s1.getTradeCode().compareTo(s2.getTradeCode());
				}
			}
		};
		Collections.sort(listAdjustSkuVO, comparator);

		returnMap.put("json", listAdjustSkuVO);
		if (errorFlg) {
			returnMap.put("errorJson", listError);
		} else {
			returnMap.put("errorJson", null);
		}
		returnMap.put("result", "success");

		return returnMap;
	}

    @Override
    public void updateOrderSku4Replace(OrderSkuVO orderSkuVO) throws Exception {
        orderSkuDAO.replaceByCondition(orderSkuVO);
    }
}
